Use Waypoints to add the same class for multiple elements

425 Views Asked by At

I want to use jQuery Waypoints to add a class to an element when it is visible in the viewport. It is simple to target one element, but I can't figure out how to use it with multiple elements. It should be something like this:

$(function() {
    const MyVariable = [
        'main.home section.blocks .text', 
        'main.page ul li',
        'main.contact .header div',
        'etc etc',
    ];
    
    $(MyVariable).waypoint(function() {
        $(this.element).addClass('animate');
    }, { 
        offset: '100%'
    });
});

Thanks for helping out!

1

There are 1 best solutions below

1
On

You don't have to keep the selectors in an array. You can do it like this :

$('.selector1,.selector2,.selector3').waypoint(function() { ...}

Or to do it as you went (with an array) but you need to go around them with a for loop:

$(MyVariable).each(function(){
var self = $(this);
 $(this).waypoint({
         handler: function(){
             self.addClass('animate');
         }
    });
})

I'm not 100% sure because I haven't tested it, but I hope it will be useful or give you guidance.