Search code examples
javascriptsticky

Stick div to top on scroll and unstick later


Currently when a div hits the top of the browser it becomes sticky (fixed) and that works perfect. What I would like is the div to unstick again after continue scrolling for another 500 pixels.

Is there a way to do this?

ps. I know the Stickem solution but that is a lot if Javascript, I have the feeling that this can be done much easier.

window.onscroll = function() {myFunction()};
var header = document.getElementById("center");
var sticky = header.offsetTop-10;
function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
#top { height:200px; background:#BFBDC1; }
#center { height:30px; background:#37323E; }
#bottom { height:4000px; background:#6D6A75; }

.sticky { position:fixed; top:0px; width:100%; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<div id="top"></div>
<div id="center"></div>
<div id="bottom"></div>


Solution

  • Simply adding an upper bound to your if condition should do the trick.

    Instead of just checking if the current offset is greater than the lower bound (sticky in this case), also check if it is less than the desired upper bound (sticky + 500).

    window.onscroll = function() {myFunction()};
    var header = document.getElementById("center");
    var sticky = header.offsetTop-10;
    function myFunction() {
      if (window.pageYOffset > sticky && window.pageYOffset < sticky + 500) { // <--here
        header.classList.add("sticky");
      } else {
        header.classList.remove("sticky");
      }
    }
    #top { height:200px; background:#BFBDC1; }
    #center { height:30px; background:#37323E; }
    #bottom { height:4000px; background:#6D6A75; }
    
    .sticky { position:fixed; top:0px; width:100%; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
    
    <div id="top"></div>
    <div id="center"></div>
    <div id="bottom"></div>