2

Similar questions have been asked, but I cannot find any help in those topics.

Take a look at this fiddle. There's a menu on the right, which allows you to scroll to other sections.

What should happen is that when you click "3" for instance, "3" in the menu gets the class "visible" (shown by a larger font size). For some reason or another, however, the first list item always gets this class. I think this happens because in the if-statement below, the first div is evaluated as true for having an offset of zero, which is not correct.

    $("body > div").each(function () {
        var $this = $(this),
            nextSection = $this.next("div"),
            offsetT = $this.offset().top;
        if (offsetT == 0) {
            $("nav a").removeClass("visible");
            $("a#" + $this.attr("id") + "-button").addClass("visible");
            console.log("a#" + $this.attr("id") + "-button");
        }
    });

Another explanation might be that something goes wrong because the function is called as a callback. I did so intentionally because when it is called as a callback, there should eb no animation left, and a container should be snapped to the top of the window: so there can only be one element that has offset == 0. But as you can see, this does not work.

The class must be set inside the SnapIt function, because the function is used else where as well.

Where did I go wrong?

Bram Vanroy
  • 27,032
  • 24
  • 137
  • 239

2 Answers2

1

I think you want when you scroll the correct number is selected then you need to change:
if (offsetT == 0) to if (offsetT == posToScroll)

Fiddle

Rational

if (offsetT == 0) will always select menu item one because the offset of this menu item is 0. Changing the if statement to if (offsetT == posToScroll) is saying select the one the window has scrolled to.

Ashley Medway
  • 7,151
  • 7
  • 49
  • 71
0

The first <div> always gets the class because it's the one at top of the window so It has 0 offset. hence

if (offsetT == 0) {

Only evaluates to true in it's case.

T J
  • 42,762
  • 13
  • 83
  • 138
  • You are right, I'm wrong. I wanted to compare to the viewable area, which should be found as follows: `el.offset().top - $(window).scrollTop()`. – Bram Vanroy Jul 17 '14 at 14:45