Search code examples
javascriptjqueryhtmlcssjquery-waypoints

"this" won't refer to the div in a JQuery listener


I have the below listener for a class .my-class (I'm using the waypoint plugin). However, if I try to call $(this).addClass("hello"), it does not add the class to the individual div that has the class and fired the listener.

On the other hand, if I call $(".my-class").addClass("hello") inside the function instead, it adds the class hello to ALL instances of .my-class, which is not what I want.

Am I misinterpreting how this is supposed to be used (I'm new to JS)? Shouldn't it refer to the single div that fires the listener and therefore add the class to that div?

$(".my-class").waypoint(function(e) {
    $(this).addClass("hello");
})

Solution

  • When using waypoint, this refers to the waypoint object. The waypoint object's element is the current div. So you would want to use

    $(".my-class").waypoint(function(e) {
     $(this.element).addClass("hello");
    })