When you hover over the div c menu, the background around it dims, but if you hold it so many times, the mouseenter & mouseleave from the diva starts blinking. I decided to set setTimeout , it turned out like this:

 $(".subcat > ul").hover(function(){ var time_id = setTimeout(function () { $(".subcat").css({ zIndex: 15 }); $(".subcat_overlay").fadeIn(); }, 1000); }, function(){ $(".subcat").css({ zIndex: 1 }); $(".subcat_overlay").fadeOut(); }); 

The problem now is that we need a variable that clears time, clearTimeout(time_id); But where to stick it, I do not understand something.

  • one
    You can make the time_id variable global ( time_id out of function), then calmly clearTimeout(time_id); before setTimeout . - Regent

3 answers 3

As suggested by @Regent, you should move the reference to the timer to global space so that you can access it after the end of the code block. And before creating a new timer, check the presence of previously created instances - in this case, delete them.

 var time_id = null; $(".subcat > ul").hover(function(){ if (time_id) { clearTimeout(time_id); } // убран var – иначе будет создаваться локальная переменная time_id = setTimeout(function () { $(".subcat").css({ zIndex: 15 }); $(".subcat_overlay").fadeIn(); }, 1000); }, function() { $(".subcat").css({ zIndex: 1 }); $(".subcat_overlay").fadeOut(); }); 

    Fade functions are queued without interrupting the previous ones. Solution - stop

     $(".subcat_overlay").stop().fadeIn() $(".subcat_overlay").stop().fadeOut() 

    Or generally without timeouts

     $(".subcat_overlay").stop().fadeOut().delay(1000).fadeIn() 

      You can write in style

       .subcat_overlay{ opacity: 0; transition: all .5s ease; } .subcat_overlay_hover{ opacity: 1; } 

      And in js

       $(".subcat > ul").hover(function(){ $(".subcat").css({ zIndex: 15 }); $(".subcat_overlay").addClass('.subcat_overlay_hover'); }, function(){ $(".subcat").css({ zIndex: 1 }); $(".subcat_overlay").removeClass('.subcat_overlay_hover'); }); 

      Or so (not sure what will work. Made a comment after seeing)

       var time_id; $(".subcat > ul").hover(function(){ clearTimeout(time_id); time_id = setTimeout(function () { $(".subcat").css({ zIndex: 15 }); $(".subcat_overlay").fadeIn(); }, 1000); }, function(){ $(".subcat").css({ zIndex: 1 }); $(".subcat_overlay").fadeOut(); });