Felipe Palazzo
Felipe Palazzo

Reputation: 21

setTimeout in a JQuery animation

I'm having a problem with the setTimeout(). I want, in the mouseout state, that the submenu slides Up after a interval (500 miliseconds). But the setTimeout() isn't working.

Like in this link: http://jsfiddle.net/felipepalazzo/Xyhvn/2/

The code:

(function($){
    $.fn.showMenu = function(options){

        var settings = $.extend({
            height  : '40px',
            speed   : '500',
            heightx : '20px'              
        }, options || {});

        return this.each(function(){
           var elem = $(this);
           var menu_timer;
            elem.hover(function(){
                $(this).stop().animate({'height' : settings.height}, settings.speed);
                    }, function(){
                      //setTimeout(function(){  
                      $(this).stop().animate({'height' : settings.heightx}, settings.speed);
                            //},500);
                    }); 
        });      
    };
})(jQuery);

Upvotes: 2

Views: 3459

Answers (3)

Jorge
Jorge

Reputation: 18237

I think that the problem relies on the element $(this), when you're inside of the function of the setTimeout the element this it's not the same. Why you don't try to save the element in a var and then executes the function

var foo = this;
setTimeout(function(){
    $(foo).stop().animate({'height' : settings.heightx}, settings.speed);
},500);

Upvotes: 1

Jonas Røssum
Jonas Røssum

Reputation: 365

Use delay()

So for example

$(this).delay(500).stop().animate({'height' : settings.heightx}, settings.speed);

Upvotes: 3

Nick Caballero
Nick Caballero

Reputation: 944

This is out of scope.

var that = this;
setTimeout(function(){
    $(that).stop().animate({'height' : settings.heightx}, settings.speed);
},500);

Upvotes: 7

Related Questions