JSFiddle - React, Tailwind, and code Playground
HTML
<div id="sidebar"></div>
<div id="user-details"></div>
CSS
body {
height: 6000px;
}
#sidebar,
#user-details {
height: 50px;
width: 50px;
position: absolute;
top: 0;
left: 0;
background: red;
}
#user-details {
top: 2000px;
background: blue;
}
JavaScript
// constants for the scrolling
var offsetSidebar = $("#sidebar").offset();
var offsetUserDetails = $("#user-details").offset();
// on scroll of window
$(window).scroll(function() {
scrollElement($("#sidebar"), offsetSidebar, 2000);
scrollElement($("#user-details"), offsetUserDetails, 4000);
});
// handle the scrolling
function scrollElement(elem, offset, boundary){
var currOffset = elem.offset();
if(currOffset.top < boundary && $(window).scrollTop() < boundary){
if ($(window).scrollTop() > offset.top) {
elem.stop().animate({marginTop: $(window).scrollTop() - offset.top});
} else {
elem.stop().animate({marginTop: 0});
}
}
}