How to stop animation on the mouse center DIV

I am trying to find a way to stop the fadeIn / fadeOut animation when the mouse is above the black area:

http://jsfiddle.net/AeZP4/1/

$(function(){ $('.text').mouseenter(function(){ $(this).stop(true,true).fadeOut(); }).mouseleave(function(){ $(this).stop(true,true).fadeIn(); }); }); 
 <div id="container"> <div class="text">s</div> </div> 
 #container{width:600px; height:100%; position:relative;} .text{position:absolute; left:0; top:0; width:200px; height:800px; background:#000000;} 

Each time the mouse moves inside this area, the function loops. How can i avoid this?

+4
source share
2 answers

It's hard to say exactly what this will be used for (which is the intention), but I would try using jQuery hover () and fadeTo () to fade the element to opacity 0.

 $(".text").hover( function () { $(this).stop(true, true).fadeTo('slow', 0) }, function () { $(this).stop(true, true).fadeTo('slow', 1) } ); 

But this may not be right depending on your use.

Example: http://jsfiddle.net/AeZP4/3/

edit: Added stop () for maxfieldens clause: http://jsfiddle.net/AeZP4/6/

+4
source

The real problem with the source code is the combination of fadeOut and mouseleave on the same element. If you fade out when your mouse is above the div, this element disappears, and so the mouseleave event will be raised. The mouseleave handler makes a call to fadeIn and the div will again be visible, which fires the mouseenter event, and we start the loop from the very beginning. This is a classic endless loop: http://jsfiddle.net/AeZP4/1/

The fadeTo function works well, because in this case the div is transparent but does not disappear (display: none).

+1
source

Source: https://habr.com/ru/post/1400462/


All Articles