iuliu.net iuliu.net - 6 months ago 11
CSS Question

.css() won't get applied after a delay

I wanted to change the background-color on a div dinamically using jQuery's

css()
and it worked, but then I tried to add some delay to it, and for some reason it stopped working. What am I missing? Here's an MVC of it:

HTML:

<div id="nodelay"></div>
<div id="delay"></div>


JS:

$("#nodelay").hover(function() {
$(this).css("background-color", 'gray');
});

$("#delay").hover(function() {
setTimeout(function() {
$(this).css("background-color", 'gray');
}, 500);
});


https://jsfiddle.net/8eabfa2t/1/

Answer

Code executed by setTimeout is run in a separate execution context to the function from which it was called. This is problematic when the context of the this keyword is important.

This means that using $(this) in the delay is problematic. Here is the edited code:

$("#nodelay").hover(function() {
     $(this).css("background-color", 'gray');
});

$("#delay").hover(function() {
    setTimeout(function() {
        $("#delay").css("background-color", 'gray');
    }, 500);
});

https://jsfiddle.net/8eabfa2t/5/

You have to explicitly reference the target, instead of implicitly using this