简体   繁体   中英

jQuery Waypoints add class when element is scrolled into view

I'm using the Waypoints plugin to check if an element is scrolled into view. I have multiple divs with class item as the user scrolls down the page, I want to add a class "viewed" to each.

$(".item").waypoint(function(){
    $(this).addClass("viewed");
    console.log("yey");
});

The console.log works, but the .addClass doesn't. Does the plugin not support $(this) ?

I finally got it working.

$(".item").waypoint(function(){
   $(this[0,'element']).addClass("viewed");
});

The this wasn't pointed at the element, so I needed to target it.

You have to be careful when calling these callback functions, and what this really means. In this instance, its probably referring to your function.

Doesn't the event trigger pass the target in the function as an argument? Try using that. If you want to know what your nested this really is, console.log it.

$(".item").waypoint(function(thing){
   $(thing).addClass("viewed");
   console.log("yey");
});

The checked answer caused loads of errors in newer version of this plugin.

This is what works for me:

$(".item").waypoint(function() {
    $(this.element).addClass("viewed");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM