Ahmed Fouad
Ahmed Fouad

Reputation: 3073

Hide element if mouse is not over it for a certain period of time

I have a dropdown menu which gets fired when mouse moves over a specific link. I want that dropdown menu to fade out if the mouse is away from the dropdown for a specific period of time?

Is it possible?

This is my jQuery for opening the dropdown menu:

$('.cartpopup').css({'display':'none'});
$('.cart-link').bind('mouseenter',function(){
    $('.cartpopup').stop(true, true).show().animate({top: 100}, 200).animate({top: 44}, 500);
});

Now how can I make the popup close automatically if it is inactive e.g. mouse not over it for certain time.

Upvotes: 1

Views: 2434

Answers (1)

cloudfeet
cloudfeet

Reputation: 12863

If you set a timer using setTimeout(), then you'll get a value returned, which you can later use to cancel that timeout.

For instance, if you had:

var hideTimer = null;
$('.cartpopup').bind('mouseleave', function() {
    hideTimer = setTimeout(function() {
        // Code to hide menu goes here
    }, 1000);
});

then when the mouse entered the item again, you could cancel the timer like so:

$('.cartpopup').bind('mouseenter', function() {
    if (hideTimer !== null) {
        clearTimeout(hideTimer);
    }
});

This way, if the mouse re-enters the item before the timer executes, then it stays visible.

Upvotes: 3

Related Questions