0

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?

8
  • You could throttle it, check here benalman.com/projects/jquery-throttle-debounce-plugin. Or check if it's already sticky. Also did you know? jQuery(function($){ //use $ } Commented Sep 16, 2013 at 3:13
  • There's no flickering when I try it -> jsfiddle.net/uGkHx 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.net/teddyrised/sE4GU 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? 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) Commented Sep 16, 2013 at 4:41

1 Answer 1

2

The 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);

  });

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.