I-NOZex
I-NOZex

Reputation: 25

How cancel jQuery mouseleave action

I want my div to slide up back to the start position when my mouse goes out, but I want my div to cancel that action and go back to its expanded position if the mouse goes back over the div again.

I need some way to stop this action:

    $(".logo").mouseleave(function(){
            $(".logo").animate({top: '-65px'}, 'slow')
    });

Here is the fiddle: http://jsfiddle.net/gaPah/6/

Upvotes: 0

Views: 1198

Answers (2)

Popnoodles
Popnoodles

Reputation: 28419

Ok finally got to the bottom of this. User clicks toggled. Div opens. User leaves div. It waits 700ms then closes. If the user interrupts it closing it reopens. If the user doesn't interrupt, it resets.

NB. .delay() does not play well with .animate() so it gets complicated, but I'm sure there would be an easier way to do this.

Also note, I've bound custom event openme to avoid writing the same animate line twice (once on mouseover and once on click of the button).

Working demo

$('#btn_panel').click(function(event){
  $(".logo").trigger('openme');
});

$('.logo').on('openme', function(){
  $(this).stop().animate({top: 0}, 700);
}).on('mouseenter', function(){
  clearTimeout($(this).to);
  if (parseInt($(this).css('top'))>-65){
      $(this).trigger('openme');
  }
}).on('mouseleave', function(){
  var el=$(this);
  $(this).to=setTimeout(function(){
    el.animate({top: -65}, 700);
  },700);
});

Upvotes: 0

Stefan Neubert
Stefan Neubert

Reputation: 1054

.stop() is the answer to your problem!

Because you want to stop the animation where it is instead of finishing it fast, you want to use

.stop(true, false)

on your element.

Here is a Demo of stop() applied to your case: http://jsfiddle.net/Ma5Xt/1/

This is the example with delay added: http://jsfiddle.net/Ma5Xt/2/

Finally, this one will allow expanding on mouseenter only when the closing animation is currently running. Otherwise, you need to click the div to reopen again: http://jsfiddle.net/Ma5Xt/3/

Upvotes: 2

Related Questions