So I have an element(link) that controls the visibility of another element(target) by hovering on it.
When the the mouse hovers the link the target is supposed to turn to visible and when the mouse leaves the target is supposed to turn invisible after 2 seconds.
So far so good. But how do I make it so that if the mouse goes hover the visible target before the 2 seconds go up, the target stays visible?
I got it to sort of work with setTimeout and clearTimeout but its really buggy and it doesn’t feel good at all.
var time = 1000;
$(".link").hover(
function () {
$('.target').css('display', 'none');
clearTimeout($(this).data('timeout'));
$('.target').css({'display': 'block'});
},
function () {
var timer = setTimeout(function() {$('.target').fadeOut(1000).delay(100).css('display', 'none'); clearTimeout(timer); }, time);
$('.target').hover(
function () {
clearTimeout(timer);
},
function () {
var timer = setTimeout(function() {$('.target').fadeOut(1000).delay(100).css('display', 'none'); clearTimeout(timer); }, time);
}
);
}
);
Any help would be greatly appreciated.
Cheers
Try re-factoring your code a bit:
Live demo
This should be really close to your described behavior. I’ve also added an extra line to display it right back when you
mouseenterwhile it’s fading out, as you can see in thehandlerIn.A couple mistakes that I took away from your code:
timervar declared inside one of themouseleavehandlers, which couldn’t be cancelled anywhere. Thetimermust be accessible in a common scope;.css, which has no effect;displaytononeafter afadeOuthas completed, it automatically does so;setTimeoutafter it has executed either.