Prashobh
Prashobh

Reputation: 9542

mouse out function is not working while we leave the mouse very slowly

normal mouse leave the function is working perfectly ,but if we are leaving the mouse very slowly then then mouse out function is not working ..

var timeoutId;
$('.box').mouseover(function(){
        var $this=$(this);
        if (!timeoutId) {
            timeoutId = window.setTimeout(function() {
            timeoutId = null;
                $this.animate({
                    marginTop:'-224px',
                    height:'300px'
                    })
    $this.find('.rotate-arrow').addClass('rotate');
    $this.find('.header-content-span').css('display','none');
                                                   },1000); }
            });
$('.box').mouseleave(function(){
        var $this=$(this);
         if (timeoutId) {
            window.clearTimeout(timeoutId);
            timeoutId = null;
            $this.animate({
                marginTop:'0px',
                height:'77px'
                })
    $this.find('.rotate-arrow').removeClass('rotate');
    $this.find('.header-content-span').css('display','block');

        }

Upvotes: 0

Views: 119

Answers (1)

Ruben Infante
Ruben Infante

Reputation: 3135

The way the code is set up, the mouseleave animation will not occur if you happen to stay hovered on the .box container for more than one second.

This is because the timeoutId is getting cleared as soon as setTimeout is triggered and the mouseleave callback contains logic to only execute the animation if the timeoutId is defined.

To resolve this, just pull the animation out of the if statement. Here is a simplified example:

var timeoutId;
$('.box').mouseenter(function () {
    var $this = $(this);
    if (!timeoutId) {
        timeoutId = window.setTimeout(function () {
            timeoutId = null;
            $this.stop().animate({
                height: '100px'
            });
        }, 1000);
    }
});
$('.box').mouseleave(function () {
    var $this = $(this);
    if (timeoutId) {
        window.clearTimeout(timeoutId);
        timeoutId = null;
    }
    $this.stop().animate({
        height: '50px'
    });
});

NOTE: I used mouseenter because it is the opposite event type to mouseleave. Depending on your specific situation, these two handlers tend to be better choices than using mouseover and mouseout due to the way they handle event bubbling for descendants of the bound objects.

jsfiddle

Upvotes: 2

Related Questions