I am trying to get a div to stick once it is scrolled out of view.
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var win = jQ(window);
var navTop = jQ('#navbar').offset().top;
win.scroll(function() {
jQ('#navbar').toggleClass('sticky', win.scrollTop() > navTop);
});
});
The problem is that with this code, navTop is not calculated correctly. If I calculate navTop in the scroll function it works as expected but with a horrible flickering effect which I assume is due to recalculating the value many times.
Why does it not calculate the value correctly after document is loaded?
I am trying to get a div to stick once it is scrolled out of view.
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var win = jQ(window);
var navTop = jQ('#navbar').offset().top;
win.scroll(function() {
jQ('#navbar').toggleClass('sticky', win.scrollTop() > navTop);
});
});
The problem is that with this code, navTop is not calculated correctly. If I calculate navTop in the scroll function it works as expected but with a horrible flickering effect which I assume is due to recalculating the value many times.
Why does it not calculate the value correctly after document is loaded?
Share Improve this question asked Sep 16, 2013 at 3:11 dooversdoovers 8,68510 gold badges45 silver badges73 bronze badges 8-
You could throttle it, check here benalman./projects/jquery-throttle-debounce-plugin. Or check if it's already sticky. Also did you know?
jQuery(function($){ //use $ }
– elclanrs Commented Sep 16, 2013 at 3:13 - There's no flickering when I try it -> jsfiddle/uGkHx – adeneo Commented Sep 16, 2013 at 3:27
- You should not calculate navTop in the scroll function, because you only need to log the initial position of the element to determine if it has been scrolled out of view. I have checked your code in a fiddle, and it seems to work just fine... jsfiddle/teddyrised/sE4GU – Terry Commented Sep 16, 2013 at 3:27
- @Terry I had a look at the fiddle and yes it works fine. Could it be flickering because I have a lot of styling applied to the navbar? – doovers Commented Sep 16, 2013 at 4:39
-
1
I wouldn't suspect the amount of styling added would have affected the rendering speed of the element in your browser, unless you're on a very slow machine, or on mobile (but anyway,
position: fixed
is problematic on many mobile browsers so you might want to selectively deactivate it) – Terry Commented Sep 16, 2013 at 4:41
1 Answer
Reset to default 2The fix I used for this problem was to fire another scroll event once to calculate the navTop variable and it works ok now.
Final Code:
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var win = jQ(window);
var navTop;
jQ(document).one("scroll", function() {
navTop = jQ('#header').offset().top;
});
win.scroll(function() {
jQ('#navbar').toggleClass('sticky', win.scrollTop() > navTop);
});
});