JSFiddle - React, Tailwind, and code Playground
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
$(window).scroll(function(){
clearTimeout(t);
t = setTimeout(function(){
$('#object').doScroll();
}, 100);
});
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){
// alert('hi');
alert('ok');
$(this).animate({'top': windowScrollTop + 'px'}, 500);
}
else if ((windowScrollTop+windowHeight) < (objectTop + objectHeight)){
alert('ok');
$(this).animate({'top': ((windowScrollTop+windowHeight) - objectHeight) + 'px'}, 500);
}
$(this).html('Top: ' + $(this).position().top + 'px');
}