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'); } });