Canceling, Delaying, and Queuing Effects

jQuery defines a few more animation and queue-related methods that you should know about. The stop() method is first: it stops any currently executing animations on the selected elements. stop() accepts two optional boolean arguments. If the first argument is true, the animation queue will be cleared for the selected elements, canceling any pending animations as well as stopping the current one. The default is false: if this argument is omitted, queued animations are not canceled. The second argument specifies whether the CSS properties being animated should be left as they are currently, or whether they should be set to their final target values. true sets them to their final values; false (or omitting the argument) leaves them at whatever their current value is.

When animations are triggered by user events, you may want to cancel any current or queued animations before beginning a new one. For example:

// Images become opaque when the mouse moves over them.
// But don't keep queueing up animations on mouse events!
$("img").bind({
    mouseover: function() {
        $(this).stop().fadeTo(300, 1.0);
    },
    mouseout: function() {
        $(this).stop().fadeTo(300, 0.5);
    }
});

The second animation-related method we’ll cover here is delay(), which simply adds a timed delay to the animation queue. Pass a duration in milliseconds (or a duration string) as the first argument and a queue name as the optional second argument (the second argument is not normally needed—we’ll ...

Get jQuery Pocket Reference now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.