$(this) does not work with waypoints

789 Views Asked by At

The $(this) attribute does not work in connection with the waypoints.js.

My Javascript:

$('.dipper').waypoint(function() {
    $(this).addClass('test');
}, { offset: '100%' });

The strange thing is that this Code is working very well on my website:

$('.dipper').waypoint(function() {
    $('.dipper').addClass('test');
}, { offset: '100%' });

In this case I am using .dipper instead of $(this). You can check it out on my website: http://www.sq-media.de/weboptimierungen/rehfeld

2

There are 2 best solutions below

2
On

The waypoint method does not run with the same context as the parent jQuery object. If you need this behaviour, you could use each to iterate over the .dipper elements:

$('.dipper').each(function() {
    var $this = $(this);
    $this.waypoint(function() {
        $this.addClass('test');
    }, { offset: '100%' });
});
0
On

As per documentation provided by waypoint, you will get element ID as

  this.element.id

So your function will look like -

    $('.dipper').waypoint(function() {
        $('#' + this.element.id).addClass('test');
    }, { offset: '100%' });

Reference taken from http://imakewebthings.com/waypoints/guides/jquery-zepto/

Note: Only additional effort is to add ID to the respective element.