views:

204

answers:

2

hey guys,

$('.file a').live('mouseenter', function() {
    $('#download').stop(true, true).fadeIn('fast');
}).live('mouseleave', function() {
    $('#download').stop(true, true).fadeOut('fast');
});

i want the mouseenter function to have a stop() and a DELAY of like a 1sec. So if i hover over #download the fadeIn should start 1second delayed. If i mouseout meanwhile the fadeIn shouldn't start. Get me?

I don't really know how to do that! any ideas? regards matt

+2  A: 

Use a setTimeout function

$('.file a').live('mouseenter', function() {
setTimeout(function(){
    $('#download').stop(true, true).fadeIn('fast');
}, 1000);
}).live('mouseleave', function() {
    $('#download').stop(true, true).fadeOut('fast');
});

setTimeout will execute the code inside the function after the specified miliseconds (in this case 1000).

sTodorov
You need to store/clear that timeout as well, if you hover in and out fast, it'll complete that fadeOut() (if it runs at all) in 200ms, then 800ms later have a queued fadeIn, even though you're not over the element. Take a look here to see what I mean: http://jsfiddle.net/nick_craver/T9t6N/ To test, quickly hover and leave the link.
Nick Craver
+2  A: 

You need to use setTimeout() in this case because of how .delay() works (and your inability to cancel it).

$('.file a').live('mouseenter', function() {
  $.data(this, 'timer', setTimeout(function() {
      $('#download').stop(true, true).fadeIn('fast');
  }, 1000));
}).live('mouseleave', function() {
  clearTimeout($.data(this, 'timer'));
  $('#download').stop(true, true).fadeOut('fast');
});

You can give it a try here.

If you use .delay() it'll dequeue the next animation for the element, regardless of if you cleared that queue earlier. So you need a timeout that you can cancel, which the above does by manually calling setTimeout() and storing the result with $.data() so you can clear it later, via clearTimeout().

Nick Craver
+1 Clean and straight-forward solution.
Tomalak