jQuery Waypoints and Changing Nav Class

Adam Robertson picture Adam Robertson · Jan 5, 2013 · Viewed 8.2k times · Source

I'm using Waypoints.js and have a question about changing the style of a nav item when a certain waypoint is reached. I'm using this code to add a class of black to the menu item menu-item-29 when the waypoint post-26 is reached. It works, however when you scroll away off the waypoint, the black class isn't removed (it stays). How can I remove the black class when the waypoint is scrolled away? Thanks.

$(document).ready(function() {
$(".post-26").waypoint(function () {
$('#menu-item-29').addClass('black');
});
});

Answer

imakewebthings picture imakewebthings · Jan 7, 2013

The waypoint function is passed a direction parameter. Use that to determine whether you should add or remove.

$('.post-26').waypoint(function(direction) {
  if (direction === 'down') {
    $('#menu-item-29').addClass('black');
  }
  else {
    $('#menu-item-29').removeClass('black');
  }
});

Or, since jQuery's toggleClass takes a second boolean parameter indicating whether to add or remove, you can just write it like this:

$('.post-26').waypoint(function(direction) {
  $('#menu-item-29').toggleClass('black', direction === 'down');
});