Adam
Adam

Reputation: 20882

JQuery + MouseOver Reset FadeOut

I have the following code that shows a drop down box which fades out and is then removed:

$('.containerDIV').show().fadeOut(10000, function() {$(this).remove();});

The above code works well but I want to update it so if a user puts a mouse over $('.containerDIV') the fade out stops and when the mouse moves out it starts again.

Hoping someone could give me a push in the right direction.

Upvotes: 2

Views: 1022

Answers (2)

Stryner
Stryner

Reputation: 7318

One solution is to use .stop(true, false), which will halt any current animation and clear the animation queue. Then you can use fadeIn(0) to show the div again instantly.

// Cache DIVs
var $containerDIVs = $('.containerDIV');

// Start Initial Fade
FadeAndRemove($containerDIVs);

// On mouseover, stop fade and show again
$containerDIVs.on("mouseover", function(e) {
  $(this).stop(true /*, false implied */ ).fadeIn(0);
});

// On mouse leave, start fade again
$containerDIVs.on("mouseleave", function(e) {
  FadeAndRemove(this);
});

// Fading function
function FadeAndRemove(els) {
  $(els).fadeOut(10000, function() {
    $(this).remove();
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="containerDIV">
  testing 123
  <select>
    <option>1</option>
  </select>
</div>

See Fiddle

Upvotes: 4

dmcknight
dmcknight

Reputation: 116

The jQuery .stop() command will interrupt any current animation, toggle, or fade in it's current position.

Have a look at this example of stop(), and also chaining multiple events to the same function.

function fadeHandler(e){
    $(this).fadeOut(5000, function(){
        $(this).remove();
    })
}

$('.containerDIV').show(fadeHandler).mouseout(fadeHandler)
$('.containerDIV').mouseover(function(){$(this).stop()})

http://jsfiddle.net/0j680L1t/

Upvotes: 1

Related Questions