开发者

jquery Canceling a delayed (setTimeout) event if something happend

In plain English, this code kicks in when an element is hovered over. When it's hovered over, I add a class and show the element, then after 5 seconds, I reverse everthing: i.e. I fade out what I had previously shown and remove the class I previously added.

$("#it").addClass('somestyle').show();
setTimeout(function(){
   $("#it").fadeOut("normal", function(){ $(this).remove开发者_如何学运维Class('somestyle'); });
}, 5000);
  • Is my code clean or hacky?
  • How to cancel those delayed actions (fadeout and class removal) if I element is hovered over again within those 5 delay seconds. If it's hovered over again, I don't want the planned delayed actions to actually happen.


Declare out of the function

    var timer;

and then inside the function:

$("#it").addClass('somestyle').show();
clearTimeout(timer);
timer=setTimeout(function(){
   $("#it").fadeOut("normal", function(){ $(this).removeClass('somestyle'); });
}, 5000);

With this code first you clear the timeout and then you set it again, so it will wait again when this function is triggered.


This article covers many methods on fading/animating on hover:

http://greg-j.com/2008/07/21/hover-fading-transition-with-jquery/

Also see the samples for how it looks:

http://greg-j.com/static-content/hover-fade-redux.html

Also there is a similar question here, with this solution:

$('.icon').hover(function() {
    clearTimeout($(this).data('timeout'));
    $('li.icon > ul').slideDown('fast');
}, function() {
    var t = setTimeout(function() {
        $('li.icon > ul').slideUp('fast');
    }, 2000);
    $(this).data('timeout', t);
});


You could set a flag when you hover, so on hover

IsHovering = 1;

when the hover finishes,

IsHovering = 0;

then only run the code in your timeout

 if(IsHovering==0)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜