JSFiddle - React, Tailwind, and code Playground
HTML
<div class="widget">
</div>
<div class="widget">
</div>
<div class="widget">
</div>
<div class="widget">
</div>
<div class="widget">
</div>
CSS
.widget {
width: 200px;
height: 200px;
margin: 20px;
display: inline-block;
border: 2px solid black;
}
.widget:hover {
border: 2px solid gold;
}
JavaScript
$( '.widget' ).mouseover( function () {
var winHeight = $( window ).height( );
var scrollTop = $( window ).scrollTop( );
var winBottom = winHeight + scrollTop;
var thisPos = $( this ).offset( ).top;
var thisPosBottom = thisPos + $( this ).height( );
// so if the widget's last pixel comes AFTER the window's last visible one, we need to trigger the scrolling function
if( thisPosBottom > winBottom )
$( 'body' ).animate( {
scrollTop: scrollTop + ( thisPosBottom - winBottom ) + 10
}, 500 );
// similarlym if it's too high and partly hidden at the top of the page
else if( thisPos < scrollTop )
$( 'body' ).animate( {
scrollTop: thisPos - 10
}, 500 );
} );