Stopping and Resetting Animations - J Query

Problem
If an animation is running, we may be required to stop it in mid flow. A common problem is seen when using a mouse over and a mouse out to trigger an animation to show and hide a particular block of content.If the mouse is run in and out of the trigger area, the animation continuously triggers;for example, the content block would keep sliding up and down until it completed the number of times it was triggered. One approach could be to use the :animated selector to filter out the element for animation.However, you may want to fade an element back out of view when the user moves the mouse away from the trigger rather than letting it complete. This can be solved with the stop() method.

Solution

We have added a CSS style to the div.box element to set the opacity to zero. Instead of having the user click the button to trigger the effect, we’re running the animation when the mouse hovers over the button. This is just to show that without the stop() calls, the animation would run out of control:

Discussion
Typically this problem would be solved using a combination of fadeIn() and fadeOut(). However, if this were used, firstly without stop(), then the effect keeps repeating each time the mouse hovers over the button.
To prevent this, we insert the stop() command before queuing on the next animation.The big advantage of this is that it stops the animation midflow. This means if the opacity of the element is at 0.5 (or 50 in IE), it will proceed with the next animation with the starting point of 0.5.
Since we are now stopping in the middle of the opacity animation, it also means we can’t properly use fadeIn() and fadeOut(). We have to explicitly state where we want to fade to. So, now we are using fadeTo(), passing in the duration and then the target opacity.
Now when the user moves their mouse back and forth over the button, the animation doesn’t repeat but fades in and out in a single smooth transition.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

J Query Topics