user2207594
user2207594

Reputation: 15

Fade on mouse out unless mouseover within set time

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

Answers (3)

user3117575
user3117575

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);
}

Live example

(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

SeanCannon
SeanCannon

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

Mex
Mex

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

Related Questions