doovers
doovers

Reputation: 8675

jQuery offset().top not working properly

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?

Upvotes: 0

Views: 10395

Answers (1)

doovers
doovers

Reputation: 8675

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

  });

});

Upvotes: 2

Related Questions