JSFiddle - React, Tailwind, and code Playground

by Md. Atiquzzaman Soikat

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<section>
  <div class="holder">
    <div class="other-div">This div should stay fixed for a while</div>
    <div class="sticky">This div will become fixed on scroll</div>
  </div>
</section>

CSS

body { margin: 0; }

section { 
  height: 2000px;
  padding-top: 100px; 
}

div {
  width: 300px;
  height: 100px;
}

.holder {
  border: 1px solid black;
  width: 500px;
  height: 200px;
  position: relative;
}

.sticky { 
  top:30px; 
  left:10px;
  background: orange; 
  z-index: 9999;
  position: relative;
  transition: all 0.3s linear;
}

.other-div {
  background: gold;
  top: 20px;
  z-index: 0;
}

.fixed {
  position: fixed;
}

JavaScript

function debounce(func, wait, immediate) {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};
var sticky = $('.sticky'),
  		otherDiv = $('.other-div'),
      initialStickyOffset = sticky.offset();
            

var handleScrolling = debounce(function(){
var scroll = $(window).scrollTop();
  if (scroll >= 70) {
  sticky.addClass('fixed');
  otherDiv.addClass('fixed');
  updateFixedPosition(otherDiv, sticky);
  }else {
  sticky.removeClass('fixed');
  otherDiv.removeClass('fixed');
  sticky.offset(initialStickyOffset)
  }
  if(getBottom('.sticky') >= getBottom('.holder')){
  	sticky.removeClass('fixed');
    otherDiv.removeClass('fixed');
    sticky.offset(initialStickyOffset)
  }
}, 100);
function getBottom(element){
var $elm = $(element);
var offset = $elm.offset();
var top = offset.top;
return top + $elm.outerHeight();

}

function updateFixedPosition(otherDiv, sticky){
var otherDivPosition = otherDiv.offset();
	if(otherDiv.hasClass('fixed') && sticky.hasClass('fixed')){
  	sticky.offset({
    	top: otherDivPosition.top + 110
    });
  }
}
$(window).scroll(handleScrolling);