How to Select All Animated Elements in jQuery
Targeting actively animating elements in jQuery is essential for
managing dynamic user interfaces and preventing animation build-up. This
article explains how to select running animations using jQuery's
built-in :animated pseudo-selector, demonstrates practical
code implementations, and covers key performance best practices.
The :animated Selector
jQuery provides a dedicated selector, :animated,
specifically designed to match all elements currently undergoing a
transition or animation managed by jQuery (such as
.animate(), .slideDown(), or
.fadeIn()).
To select every animated element on the page, use:
$(":animated")Common Usage Examples
1. Selecting Specific Animated Elements
You can combine :animated with tag names, classes, or
IDs to limit the scope of the selection:
// Select all animated <div> elements
$("div:animated");
// Select animated elements with a specific class
$(".notification:animated");2. Stopping Active Animations
A frequent use case is halting animations that are currently in progress to prevent queue buildup caused by rapid user events:
// Stop all active animations immediately
$(":animated").stop();
// Stop animations on a specific container's children
$("#carousel").find(":animated").stop(true, true);3. Checking If an Element Is Currently Animating
To determine if a specific element is mid-animation before triggering
a new action, use the .is() method:
if ($("#menu").is(":animated")) {
console.log("The menu animation is currently running.");
} else {
$("#menu").slideToggle();
}Performance Considerations
Because :animated is a custom jQuery selector rather
than a standard CSS specification, browsers cannot optimize it using the
native querySelectorAll API.
To maintain optimal DOM performance:
- Narrow the scope: Avoid running
$(":animated")across the entire document. Instead, scope it down using a parent element, such as$("#wrapper").find(":animated"). - Use
.filter(): Query standard elements first using native-friendly selectors before filtering:
$(".slider-item").filter(":animated");