Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop the animation on mouseenter of a DIV

Tags:

html

jquery

css

I'm trying to find a way to stop the fadeIn/fadeOut animation when the mouse is over 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 move inside that area, the function is looped. How can I avoid this?

like image 479
Warface Avatar asked Mar 08 '12 20:03

Warface


2 Answers

It's hard to tell exactly what this will be used for (what the intent is), but I would try to use the jQuery hover() function and use fadeTo() to fade the element to 0 opacity.

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

But again this may not be right depending on your use.

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

edit: Added stop() per maxfieldens suggestion: http://jsfiddle.net/AeZP4/6/

like image 57
jyoseph Avatar answered Oct 14 '22 02:10

jyoseph


The real problem with the original code is the combination of fadeOut and mouseleave on the same element. If you fadeOut while your mouse is over the div this element disappears and therefore the mouseleave event will be triggered. The mouseleave handler makes a fadeIn call and the div will be visible again which triggers the mouseenter event and we start the loop from the beginning. This is a classic endless loop: http://jsfiddle.net/AeZP4/1/

the fadeTo function is working well because in this case the div is transparent but didn't disappear (display: none).

like image 29
Simon Avatar answered Oct 14 '22 02:10

Simon