Search code examples
javascriptjquerymouseeventmouseentermouseleave

How to stop the repeat of the jQuery functions mouseenter() and mouseleave()?


Problem: When i hover the mouse on the div block, the ul list items are displayed with a fadein, and when i distract the mouse from the div block, the ul list items are fadeing out, and when i do the same action fast 5,6,7 or more times and when i do nothing with the mouse, the functions mouseenter() and mouseleave() are repeating because of the fadeing duration. I want that for example if the function mouseenter() has started, the other function mouseleave() would not start even if the user has the mouse distracted from the div block, the mouseleave() function must wait until the mouseenter() function has finished his job, and then the mouseleave() function can start, and so on.. How can do it?

Demo: https://jsfiddle.net/qcvL1xjg/

HTML:

<div class="block"></div>
<ul class="responser">
    <li>Home</li>
    <li>Product</li>
    <li>About</li>
</ul>

CSS:

.block {
    width: 100px;
    height: 100px;
    background-color: red;
}

jQuery:

$(document).ready(function() {
     $('.responser').hide();

   $(".block").mouseenter(function() {     
           $('.responser').fadeIn(1250);           
   });

   $('.block').mouseleave(function() {     
           $('.responser').fadeOut(1250);         
   });
});

Solution

  • You can use,.stop() method for stopping the current animation.

      $(".block").hover(
        function () {
            $('.responser').stop().fadeIn(1250);
        }, function () {
            $('.responser').stop().fadeOut(1250);
        });
    

    or

     $(".block").mouseenter(function() {     
               $('.responser').stop().fadeIn(1250);           
       });
    
       $('.block').mouseleave(function() {     
               $('.responser').stop().fadeOut(1250);         
       });
    

    Fiddle