0

I'd like a navigation bar to stick (position:fixed) when it hits the top of the window. But I also want the element to go back to normal positioning if the user scrolls back up.

The following code makes the element stick, but as you scroll, the event keeps firing, causing the element to flash in and out. If I remove the 'else removeClass()', it's smooth (and stops flashing) but the element stays fixed after I scroll back up to the top. Thoughts?

Relevant CSS:

.fixed-object { width:100%; background-color:tomato; } .stick { position:fixed; top:0; } 

jQuery:

 $(window).scroll(function(){ var elementDepth = $('.fixed-object').offset().top; var scrollDepth = $(window).scrollTop(); if (scrollDepth >= elementDepth) { $('.fixed-object').addClass('stick'); } else { $('.fixed-object').removeClass('stick'); } }); 
5
  • 1
    can make a quick fiddle ? Commented Dec 11, 2013 at 4:13
  • i've never done one before, but I'll try. Commented Dec 11, 2013 at 4:15
  • till you make one , check this stackoverflow.com/questions/20486131/… Commented Dec 11, 2013 at 4:18
  • so from what i get if user scrolls to bottom the nav bar should have top:0 , and fixed position , else just keep it as last seen !! right ? Commented Dec 11, 2013 at 4:20
  • here's a fiddle. I commented out @arun's solution, but both are there. Neither of them are flashing like they were for me locally, but neither are returning the element to its original height either. jsfiddle.net/B6mPn Commented Dec 11, 2013 at 4:31

1 Answer 1

2

Make it as simple.....

Declare the elementDepth as GLOBAL variable... it will work

var elementDepth = $('.fixed-object').offset().top; $(window).scroll(function(){ var scrollDepth = $(window).scrollTop(); if (scrollDepth >= elementDepth) { $('.fixed-object').addClass('stick'); } else { $('.fixed-object').removeClass('stick'); } }); 

Live Demo

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

2 Comments

bingo! why does that work, if you don't mind? --just curious :)
elementDepth was being recalculated everytime you scroll. If there was any "jitter" in the reported values from the browser, voila, flickering element. Using it as a global caused it to be calculated once and such no "jitter" can get in.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.