Search code examples
javascriptjqueryscrolljquery-waypoints

jquery waypoints, activate when in center of viewport instead of top?


All the documentation talks about when the waypoint reaches the top of the viewport, but I would like the trigger to happen when any part of the waypoint is in the center of the viewport.

This code works fairly well if I'm scrolling down, but when I scroll up it doesn't work, obvoiusly.

$('.section').waypoint(function(direction) {
    highlight('#' + this.id);
}, {
    context: '#scroll',
    offset: function (direction) {
        return $(this).height();
    }
});

I tried the code below and a couple variants and it never even hits either of the return statements.

$('.section').waypoint(function(direction) {
    highlight('#' + this.id);
}, {
    context: '#scroll',

    offset: function (direction) {
        if (direction == 'down') {
            return -$(this).height();
        } else {
            return 0;
        }
    }
});

So now I'm trying this, based on waypoint examples, but $active.id doesn't work like this.id so my function "highlight" fails.

$('.section').waypoint(function (direction) {
    var $active = $(this);
    if (direction == 'down') {
        $active = $active.prev();
    }
    if (!$active.length) {
        $active = $(this);
    }
    highlight($active.id);
}, {
    context: '#scroll',
    offset: function (direction) {
        return $(this).height();
    }
});

Solution

  • The offset option does not take a direction parameter. I'd love to know if you got that from somewhere in the documentation because if there's a section using direction in an offset function, it's a mistake.

    You can tell a waypoint to trigger when the top of the element hits the middle of the viewport by using a % offset:

    offset: '50%'
    

    If you need to have a different offset when scrolling up versus scrolling down, this is best accomplished by creating two different waypoints:

    var $things = $('.thing');
    
    $things.waypoint(function(direction) {
      if (direction === 'down') {
        // do stuff
      }
    }, { offset: '50%' });
    
    $things.waypoint(function(direction) {
      if (direction === 'up') {
        // do stuff
      }
    }, {
      offset: function() {
        // This is the calculation that would give you
        // "bottom of element hits middle of window"
        return $.waypoints('viewportHeight') / 2 - $(this).outerHeight();
      }
    });