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);
})