JSFiddle - React, Tailwind, and code Playground
by Jaybles
HTML
<div id='object'>Top: 0px</div>
CSS
body{height:10000px;width:400px;background:url(http://dummyimage.com/60x40/eee/aaa.png&text=body)}
#object{height:200px; width:200px;background:#f00;position:absolute;top:0;left:0;}
JavaScript
//http://stackoverflow.com/questions/5273453/using-jquery-to-keep-scrolling-object-within-visible-window
$(window).scroll(function(){
clearTimeout(t);
t = setTimeout(function(){
$('#object').doScroll();
}, 750);
});
var t=null;
$.fn.doScroll= function() {
var objectTop = $(this).position().top;
var objectHeight = $(this).outerHeight();
var windowScrollTop = $(window).scrollTop();
var windowHeight = $(window).height();
if (windowScrollTop > objectTop)
$(this).animate({'top': windowScrollTop + 'px'}, 500);
else if ((windowScrollTop+windowHeight) < (objectTop + objectHeight))
$(this).animate({'top': ((windowScrollTop+windowHeight) - objectHeight) + 'px'}, 500);
$(this).html('Top: ' + $(this).position().top + 'px');
}