0

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!

arvanderkamp
  • 171
  • 4
  • 15

1 Answers1

1

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.

Todor Markov
  • 507
  • 5
  • 12
  • Thanks for your help Todor. Yes, the first options works, but I need to add the Waypoint function for lots of elements. So, for the sake of overview and proper code I want to put each element on a different rule. I tried your array example, but unfortunately it doesn't work. Any other thoughts? – arvanderkamp Oct 06 '21 at 07:10