Peanut
Peanut

Reputation: 3295

setTimeout won't execute the function

I even looked at this and this solution still didn't help me : Execute a function after X seconds in jquery

Here is my code:

// featured bounce
$('#featured .animated').hover(function() {
    $(this).addClass('bounce');
    setTimeout( function(){
        $(this).removeClass('bounce');},
        1300
    );
});

The adding of the class works, but the setTimeout ordeal will not work. It won't even execute and not javascript error is thrown in the Chrome console. I feel like I have everything typed out correctly.. the class on the .animated object after the addClass() looks like this:

"animated bounce"

And the animation plays, but then it NEVER removes the "bounce" from the class attribute.

Any help?

Upvotes: 0

Views: 121

Answers (3)

Mulan
Mulan

Reputation: 135197

Using Function.prototype.bind correctly, you can avoid cheap context hacks like var that = this.

// featured bounce
$('#featured .animated').hover(function() {
    var elem = $(this);
    elem.addClass('bounce');
    setTimeout(elem.removeClass.bind(elem, 'bounce'), 1300);
});

Side Note: Function.prototype.bind is an ES5 addition and browser support needs to be considered. See the compatibility table at the bottom of the MDN article on the function.

Upvotes: 3

Naftali
Naftali

Reputation: 146302

$('#featured .animated').hover(function() {
    $(this).addClass('bounce');
    (function(that) {
        setTimeout( function(){
            // use `that` instead of `this`
            $(that).removeClass('bounce');
        }, 1300);
     })(this); //pass `this` into this function
});

Upvotes: -2

epascarello
epascarello

Reputation: 207501

The scope of this is pointing at window, not the element you expect.

$('#featured .animated').hover(function() {
    var elem = $(this);
    elem.addClass('bounce');
    setTimeout( function(){
        elem.removeClass('bounce');},
        1300
    );
}); 

Upvotes: 1

Related Questions