Ricardo Binns
Ricardo Binns

Reputation: 3246

Fire an event handler after a certain amount of time

What I need is this:

If the user hover the element for more then 1 second, the event will happen, otherwise it should not.

I tried using the setTimeout() but it just delays the event and does not cancel it when the mouse leaves the element.

Are there any other ways to solve this problem?

$(".optionCont").live('mouseover', function(e){
    var $this = $(this);
    setTimeout(function(){
        $(".dropMenuCont").stop(true,true).slideUp(200);
        if($this.next().css("display") == "none"){
            $this.next().stop(true,true).slideDown(200);
        }else{
            $this.next().stop(true,true).slideUp(200);
        }
            e.preventDefault();
            e.stopPropagation();
            return false;

    }, 1000);
});

Upvotes: 0

Views: 1285

Answers (1)

Felix Kling
Felix Kling

Reputation: 816422

You could listen to the mouseenter and mouseleave events and clear the timer in the mouseleave event handler:

$(".optionCont").live('mouseenter', function(e){
     var $this = $(this);
     var timer = setTimeout(function(){
          //...
     }, 1000);
     $this.data('timer', timer);
}).live('mouseleave', function(e) {
     clearTimeout($(this).data('timer'));
});

Update:

Btw. these lines in the setTimeout callback

e.preventDefault();
e.stopPropagation();
return false;

won't have any effect, as by the time the callback is executed, the event already bubbled up and triggered the default action (not to mention that return false from the callback does not mean anything). You have to put them directly into your event handler.

Upvotes: 6

Related Questions