Reputation: 15
I am looking for a solution for the following problem: Om mouseover a div fades in. On mouseout it fades out again. Simple and this works, but I would like to set a condition that the fadeing Out only happens if mouseover doesn't occur again within a set time, say 2s. Simple delay() does not work since it will then happen anyway... Is there a way to set some kind of timer to cancel a function from running if an event triggers within this time?
Upvotes: 0
Views: 606
Reputation:
Although this is probably really unhelpful, to add contrast to the jQuery answers, I made a pure JavaScript answer....
document.getElementById("test").onmouseover = function(){
this.style.opacity = "1";
if (typeof exTimeout !== "undefined") clearTimeout(exTimeout);
}
document.getElementById("test").onmouseleave = function(){
exTimeout = setInterval(function(){
document.getElementById("test").style.opacity = "0"
}, 2000);
}
(Side note, this only changes opacity so it still takes up physical space on the page, and it also requires CSS3 transitions to be made smooth)
Upvotes: 1
Reputation: 77966
$('#foo').hover(function() {
var $bar = $('#bar');
clearTimeout($bar.data('fadeOutTimer'));
$bar.fadeIn();
}, function() {
var $bar = $('#bar');
$bar.data('fadeOutTimer', setTimeout(function() {
$bar.fadeOut();
}, 3000));
});
Demo : http://jsfiddle.net/5oLcfzj1/
Upvotes: 2
Reputation: 999
<div class=container1></div>
<div class=container2></div>
$('container1').mouseover(function(){
$('container2').show(500);
});
$('container1').mouseout(function(){
setTimeout(function(){
$('container2').hide(500);
}, 2000);
});
Upvotes: 0