Mark Boulder
Mark Boulder

Reputation: 14277

Mouseenter mysteriously activated when it shouldn't

I have this box which, on hover, plays a loader animation and then expands after 2 seconds:

http://jsfiddle.net/frank_o/WwD5V/23/embedded/result/

But how come it expands immediately (with no loader animation) if I move my mouse in the following V-shaped motion?

enter image description here

var timeout;

$('.wrapper').bind('mouseenter', function () {
  if(!$('.wrapper').hasClass('expanded')) {

    $('.loader').show();

    // http://stackoverflow.com/questions/23922264/jquery-animate-goes-bananas-despite-stop

    var timeoutHandle = $(this).data('timeout') || 0;

    if (timeoutHandle > 0) clearTimeout(timeoutHandle);

    timeoutHandle = setTimeout(function () {
        $('.wrapper').animate({
            width: '100%'
        }, 200);

        $('.wrapper').addClass('expanded');
    }, 2000);

    $(this).data('timeout', timeoutHandle);
  }
}).mouseleave(function () {
    $('.loader').hide();

    $('.wrapper').animate({
        width: '120px'
    }, 200);

    $('.wrapper').removeClass('expanded');
});

Upvotes: 0

Views: 50

Answers (1)

showdev
showdev

Reputation: 29168

When you mouseover, a timeout is set. When you mouseleave, the timeout continues to run. It seems that you need to clear your timeout upon mouseleave.

I did several things to achieve this:

1) Increase the scope of the variable timeoutHandle at the top of the script:

var timeoutHandle;

2) Remove the var from your timeout definition in mouseenter:

timeoutHandle = $(this).data('timeout') || 0;

3) Clear the timeout on mouseleave:

clearTimeout(timeoutHandle);

Working Example (jsfiddle)


As you mentioned, the expanded class is no longer needed. I removed it in the fiddle, below.

Also, I added code to stop any current animation on mouseleave, in case the box is in the middle of animating. I slowed down the "expand" animation to illustrate this more clearly.

$('.wrapper').stop(true,false).animate({
    width: '120px'
}, 200);

Working Example (jsfiddle)

Upvotes: 1

Related Questions