JSFiddle - React, Tailwind, and code Playground
by secretgspot
HTML
<div id="content">
<div id="box">box</div>
</div>
CSS
#content {
position: relative;
background: url(http://www.clker.com/cliparts/c/c/2/a/1194989366182291164pattern-dots-square-grid-02.svg.med.png);
height: 2000px;
}
#box {
position: absolute;
right: 20px;
top: 250px;
background: #333;
width: 100px;
padding: 40px 0;
text-align: center;
color: white;
}
#content .follow {
position: fixed;
top: 0;
}
JavaScript
var boxTop = $("#box").offset().top;
var ducumentScroll = 0;
$(document).scroll(function(){
ducumentScroll = $(this).scrollTop();
if (boxTop <= ducumentScroll) {
$("#box").addClass('follow');
} else if (boxTop >= ducumentScroll) {
$("#box").removeClass('follow');
}
});