1

I'm trying to add class to next element after .color inside parent div, and then after 800 miliseconds I want that this class to be removed.

My code looks like this:

$(".color").click( function () { 
  $(this).next().addClass("class");
  setTimeout(function(){ $(this).next().removeClass("class"); }, 800); 
})

Adding class works fine, but I have issue with removing it. The problem is probably in scope of setTimeout() function, but i can't figure it out.

Maybe some short explanation could help me. Thank you.

A. Meshu
  • 4,053
  • 2
  • 20
  • 34
  • 1
    Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – Taplar Dec 20 '18 at 22:59

1 Answers1

4

This can be resolved via the use of an arrow function for the handler of your call to setTimeout() as shown:

$(".color").click( function () {

    $(this).next().addClass("class");

    // Use arrow function to resolve the "access to context" problem
    setTimeout(() => { $(this).next().removeClass("class"); }, 800); 
})

The idea of this in arrow functions is slightly different to that of regular functions.

Unlike regular functions that, by default, have their own this instance, arrow functions instead inherit this from their calling context. That means the this of the arrow function above would be the same as the this of the click() function. In situations like yours, the use of arrow functions in this way can be quite useful, allowing direct and convenient access to the calling context from a nested function (compared to what is shown below).

Alternatively, if your target browser doesn't support arrow functions, you can resolve this issue by the following method:

$(".color").click( function () {

    var colorNext = $(this).next();        
    colorNext.addClass("class");

    setTimeout(function () { colorNext.removeClass("class"); }, 800); 
})
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65