Ads 468x60px

Labels

Tuesday, May 1, 2012

Stopping animations with the stop() method

In the previous chapter, we saw how we could do custom animations using the animate() method and how we could have several animations after each other, by making several animation calls and thereby using the animation queue of jQuery. However, sometimes you need to stop an animation before it finishes, and for this, jQuery has the stop() method. It works for all effects related jQuery functions, including sliding, fading and custom animations with the animate() method. Here's an example where we use it:

Show box   
Stop



To make the example a bit more compact, I have used inline calls in the onclick events of the two links. When you click the first link, the slideDown() method is used on our div element, starting a slow slide down. A click on the second link will kill the current animation being performed on the selected element. This is the default behavior of the stop() method, but two optional parameters allows us to do things differently. The first parameter specifies whether the animation queue should be cleared or not. The default is false, which means that only the active animation will be stopped, allowing any queued animations to be performed afterwards. The following example will demonstrate that:
Show box   
Stop   
Stop all   
Reset


We have added a second animation to the "Show box" link. This will slowly slide down the box, and once done, slide it up again. The queue system makes sure that these steps are performed in sequence. Now, click the "Reset" link to have the box hidden again and then click the "Show box" link once more, followed by a click on "Stop". You will see that the first animation is stopped, allowing for the second animation to be executed. However, if you try again and click on the "Stop all" instead, the true value passed will make sure that the entire queue is cleared and that all animation on the element is stopped. The second parameter tells jQuery whether you would like for it to just stop where it is, or rush through the animation instead, allowing for it to finish. This makes a pretty big difference, because as you can see from the first example, once you hit stop, the default behavior is to simply stop the animation where it is and leave it like that. The following example will show you the difference:
Show box   
Stop   
Stop but finish   
Reset


Try the two "Stop" variations - the first will stop immediately, while the second one will rush the animation to finish.

0 comments:

Post a Comment

 

Sample text

Sample Text

Sample Text