Spiegel Spiegel - 1 month ago 11
Javascript Question

Jquery mouseleave setTimeout don't work

I have a code jquery

$( ".name" )
.on( "mouseenter", function() {
$(this).find("ul").css({"font-size": "20px",
'color': "red"});
})
.on( "mouseleave", function() {
setTimeout(function () {
$(this).find("ul").css({"font-size": "12px",
'color': "blue"});
}, 5000);
});


The first part is working, but second is broken (

Answer

This is a scoping problem. $(this) inside the setTimeout doesn't refer to $('.name'). You can fix this by setting a variable for this at the correct level and referring to that.

.on("mouseleave", function() {

    var self = $(this);

    setTimeout(function() {
        self.find("ul").css({
            "font-size": "12px",
            'color': "blue"
        });
    }, 5000);
});