Reputation: 5119
I'm trying to find a way to stop the fadeIn/fadeOut animation when the mouse is over the black area:
$(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?
Upvotes: 5
Views: 1761
Reputation: 381
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).
Upvotes: 1
Reputation: 5455
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/
Upvotes: 4