2

So i have a long scrolling 1page website with a fixed navigation bar.

With this navigation bar I would like to track its .offset().top so I may add or remove classes based on the offset from the top of the window.

Live code link

Example (this is my logic but i cannot make the jQuery alert even work.

$(window).scroll(function () {
  var elem = $('.navigation');
  var topValue = offset.top;
  if (topValue > 400) {
    alert(topValue);
  }
});
Zuul
  • 16,217
  • 6
  • 61
  • 88
Armeen Moon
  • 18,061
  • 35
  • 120
  • 233

2 Answers2

3

Try jQuery Waypoints. Instead of specifying an offset, you use the elements on your page to trigger a callback whenever they come into view:

$(function () {
  $("#map").waypoint(function () {
    alert("Scrolled to #map");
  });
});

Edit:

But to properly answer your question, your navigation will always be in the same position because position: fixed positions your element relative to the viewport, not the page. If you want to do this without Waypoints, just check the body tag’s scrollTop:

$(function () {
  $(window).scroll(function () {
    var offset = $("body").scrollTop();
    if (offset > 400)
      alert("Scrolled to 400");
  });
});
Todd Yandell
  • 14,656
  • 2
  • 50
  • 37
0

The issue with your code is that you are using offset.top, but you have no offset variable declared, meaning that the .top is not returning anything.

It seems that You've looked at the jQuery documentation for the offset(), but haven't understood/read the example properly.

At the documentation, they are initializing a variable:

var offset = $(this).offset();

And then extracting the .top and .left values:

alert(" coordinates: ( " + offset.left + ", " + offset.top + " ) ");

Looking at the web-page from your link, you don't need a very extensive script to check how much did the user scroll. This small function gives you what you need:

See this working Fiddle Example!

// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

More reading about this can be found at this stackoverflow answer.

Community
  • 1
  • 1
Zuul
  • 16,217
  • 6
  • 61
  • 88