jqueryjquery-waypoints

Highlight nav link when scrolling down to div using waypoints


I've been searching on this for a while now and I couldn't find the right solution for me. I kind of put things together from different articles but I can only get the links to highlight and it doesn't seem to remove class when I scroll back up. Also, when I scroll down all the links get highlighted not just the one link associated with the div.

 var $navLinks = $('#about-nav > a'); 

      $navLinks.each(function() {
        var $self = $(this);

        $(this).waypoint({
            handler: function() {
              $self.addClass('current');
          }
       });
     });

Solution

  • Waypoints are usually just about connecting links to content through hashtags and matching ids. I don't see that linking in your example, which is probably why it doesn't work for you... Or maybe it would have been there if you had been more generous with the whole context ;)

    You need a relay that pass the current class from the previous to the next and you need a link between the content and the nav link most commonly something like a hashtag that points to the content.

    The idea is:

    <nav>
      <li><a href="#waypoint1">Go to content1</a></li>
      <li><a href="#waypoint2">Go to content2</a></li>
      <li><a href="#waypoint3">Go to content3</a></li>
    </nav>
    

    And then you've got a content block with all your-waypoints from waypoint1 to waypoint3 inside, like:

    <div id='your-waypoints'>
       <div id='waypoint1' class='waypoint'>
          blah-blah-blah
       </div>
       <div id='waypoint2' class='waypoint'>
          blah-blah-blah
       </div>
       <div id='waypoint3' class='waypoint'>
          blah-blah-blah
       </div>
    </div>
    

    Connecting the dots through script, like:

    function getWaypointNavRef( WaypointId ) {
        return $('nav a[href="#' + WaypointId + '"]');
    }
    
    var lastNavRef = null;
    function WaypointRelay( WaypointId ) {
       var nextNavRef = getWaypointNavRef( WaypointId );
       if (lastNavRef)
          $(lastNavRef).removeClass('current');
       $(nextNavRef).addClass('current');
       lastNavRef = nextNavRef;
    }
    

    Which is called from the handler:

    $('#your-waypoints > .waypoint').each(function () {
            new Waypoint({
            element: document.getElementById(this.id),
            handler: function (direction) {
                WaypointRelay(this.element.id);
            },
            context: document.getElementById('your-waypoints')
        });
    });
    

    Which means that is actually the content that links to the nav when you scroll down the page...