0

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>

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

This is definitely on the right track, thanks but after 500px it now suddenly disappears, is it possible to scroll it out smoothly?
@ErwinvanEkeren If you are using jQuery, you can use jQuery's animate() function.
0

Add some additional conditional in your function testing against window.scrollY

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.