1

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).removeClass('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.
drummer
  • 1,211
  • 3
  • 16
  • 16

3 Answers3

4

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.

mck89
  • 18,918
  • 16
  • 89
  • 106
0

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);
});
Community
  • 1
  • 1
Espo
  • 41,399
  • 21
  • 132
  • 159
0

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)
Paul
  • 5,514
  • 2
  • 29
  • 38