JQuery mouseover mouseout opacity

function hoverOpacity() { $('#fruit').mouseover(function() { $(this).animate({opacity: 0.5}, 1500); }); $('#fruit').mouseout(function() { $(this).animate({opacity: 1}, 1500); }); } 

This is my function that animates the div#fruit , and it works.

The problem is this; When you mouseout before completing the mousein animation, it must complete the animation before starting mouseout . (hope that makes sense)

This is usually not noticeable, but with a long duration it is noticeable.

Instead of completing the animation, I want the animation to pause and go back to its original state.

+4
source share
4 answers

You are looking for the stop function, followed by show (or hide or css ), depending on what state you want opacity in the end).

 function hoverOpacity() { $('#fruit').mouseover(function() { $(this).stop(true).animate({opacity: 0.5}, 1500); }); $('#fruit').mouseout(function() { $(this).stop(true).animate({opacity: 1}, 1500); }); } 

true tells the animation to go to the end. If this is the only element animation, this should be fine; otherwise, as I said, you can look at css to explicitly set the desired opacity.

Separately, you can use mouseenter and mouseleave rather than mouseover and mouseout , for two reasons: 1. mouseover repeated when the mouse moves over an element and 2. Both bubbles are mouseover and mouseout , and therefore, if your "fruit" element has children, You will also receive events from them that destabilize this type of animation.

+5
source

You need to add a .stop() call before animating it to clear the current and any subsequent animation:

 function hoverOpacity() { $('#fruit').mouseover(function() { $(this).stop(true).animate({opacity: 0.5}, 1500); }); $('#fruit').mouseout(function() { $(this).stop(true).animate({opacity: 1}, 1500); }); } 
+2
source

Try the following:

 function hoverOpacity() { $('#fruit').mouseover(function() { $(this).stop(true, true).animate({opacity: 0.5}, 1500); }); $('#fruit').mouseout(function() { $(this).stop(true, true).animate({opacity: 1}, 1500); }); } 

This should stop the animation, clear the queue (first arg) and go to the end (second argument), you can change / hang with arguments as needed.

+1
source

try it:

 function hoverOpacity() { $('#fruit').hover(function() { $(this).animate({opacity: 0.5}, 1500); }, function() { $(this).animate({opacity: 1}, 1500); }); } 
0
source

All Articles