sam sam - 4 months ago 9
Javascript Question

Prevent hovering effect after pointer moves away

I want to display an element on hover. Following code does it. However there is a problem, if you hover over multiple times, the element keeps displaying as many times when the cursor goes away.

Hover over the link multiple times in the demo to understand the problem.



$('li').hover(function() {
$(this).find('.box').delay(100).fadeIn();
}, function() {
$(this).find('.box').delay(100).fadeOut('fast');
});

.box {
color: #FFF;
width: 200px;
background: #000;
position: absolute;
display: none;
margin-top: 50px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="images">
<li>
Show
<div class="box">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce eu condimentum odio, non congue quam. Cras feugiat nulla at mattis semper.
</div>
</li>
</div>





JSFiddle https://jsfiddle.net/e99afrg8/

Answer

jQuery animations are queued by default. So, as you hover on and off rapidly, all those animations are queued up and continue playing after you stop hovering.

I suggest using stop() to "[s]top the currently-running animation on the matched elements."

In my example, I have also chosen to clear the queue but not jump to the end of the current animation. You may want to experiment with those values and see which behavior you prefer.

.stop( [clearQueue ] [, jumpToEnd ] )

$('li').hover(function() {
  $(this).find('.box').stop(true,false).delay(100).fadeIn();
}, function() {
  $(this).find('.box').stop(true,false).delay(100).fadeOut('fast');
});
.box {
  color: #FFF;
  width: 200px;
  background: #000;
  position: absolute;
  display: none;
  margin-top: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="images">
  <li>
    Show
    <div class="box">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce eu condimentum odio, non congue quam. Cras feugiat nulla at mattis semper.
    </div>
  </li>
</ul>