I’m trying to write a code that adds a class to a div for a limited time, and then removes it.
I tried using javascript’s setTimeout, and jQuery’s delay, but nothing works.
The element is SET but never REMOVED.
Here’s the come I came up with:
window.onload = function() {
$(".button").click(handler);
}
function handler() {
$(this).addClass("onclick");
setTimeout(function() { $(this).removeClass("onclick"); }, 3000); // JS's setTimeout
$(this).addClass("onclick").delay(3000).removeClass("onclick"); // jQuery's delay
}
I don’t get what’s wrong… I even tried writing a second handler for the setTimeout function.
Thanks in advanced.
The problem you’re having is that
thisis different within the function you’re passing tosetTimeoutthan it is outside it. The usual fix is to use the closure by creating a variable to hold it, and using the variable instead:There I’ve also use the var to cache the result of
$(this)because there’s no point in doing it more than once.More background:
In JavaScript, unlike some languages that look similar,
thisis defined entirely by how a function is called. When you usesetTimeout, the way the function gets called will makethisbe the global object (window, on browsers), so that’s why$(this).removeClass(...)wasn’t working.More on
thisif you’re interested:this