Search code examples
jquerycssjquery-plugins

jQuery waypoints plugin - remove class when out of view


I'm using waypoints plugin

$('.thing').waypoint(function(direction) {
    jQuery(".block7").addClass("active");
});

Now I want to modify it to make the added class removed from the .thing element immediately when its out of browser view. What do I add to code above?


Solution

  • You can do it by looking at direction. If the same offset works for both adding and removing the class, you can put this in your handler

    var waypoint = new Waypoint({
      element: $('.thing'),
      handler: function(direction) {
        if (direction == 'up') {
          $(".block7").removeClass("active");
        } else {
          $(".block7").addClass("active");
        }
      },
      offset: '100%'
    })
    

    Or if you want different offsets, you can make 2 waypoints.

    var waypoint = new Waypoint({
      element: $('.thing'),
      handler: function(direction) {
        $(".block7").addClass("active");
      },
      offset: '75%'
    })
    
    var waypoint2 = new Waypoint({
      element: $('.thing'),
      handler: function(direction) {
        if (direction == 'up') {
          $(".block7").removeClass("active");
        }
      },
      offset: '100%'
    })
    

    Here's a codepen - http://codepen.io/anon/pen/oZqMdJ