Skip to main content
SeleniumDecoded

Wait for a CSS Animation or Transition to Finish

Wait until a sliding drawer, modal or accordion has stopped moving before clicking, using the Web Animations API with a position-stability fallback.

Stable Verified against Selenium 4.52.0

Problem

A side drawer slides in over 300 ms. elementToBeClickable passes as soon as the drawer’s button is visible and enabled, which happens on the first animation frame. The click lands where the button was, hits something else, or throws ElementClickInterceptedException. Adding a 500 ms sleep works until someone changes the animation duration.

Solution

Ask the browser whether the element (and its descendants) still have running animations or transitions, using element.getAnimations(). Ignore infinite animations like spinners, which never finish by design. For older custom JavaScript animations that do not use CSS, fall back to waiting until the element’s position stops changing.

Wait until no finite animation is running
Selenium 3 & 4 Stable
private static final String ANIMATING = """
return arguments[0].getAnimations({ subtree: true }).some(a =>
a.playState === 'running' &&
a.effect && a.effect.getComputedTiming().iterations !== Infinity);
""";
public static WebElement waitForAnimationEnd(WebDriver driver, By locator, Duration timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement el = wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
JavascriptExecutor js = (JavascriptExecutor) driver;
wait.until(d -> !(Boolean) js.executeScript(ANIMATING, el));
return el;
}
driver.findElement(By.id("open-filters")).click();
WebElement drawer = waitForAnimationEnd(driver, By.cssSelector(".filter-drawer"), Duration.ofSeconds(5));
drawer.findElement(By.cssSelector("button[type='submit']")).click();
ANIMATING = """
return arguments[0].getAnimations({ subtree: true }).some(a =>
a.playState === 'running' &&
a.effect && a.effect.getComputedTiming().iterations !== Infinity);
"""
def wait_for_animation_end(driver, locator, timeout=5):
wait = WebDriverWait(driver, timeout)
el = wait.until(EC.visibility_of_element_located(locator))
wait.until(lambda d: not d.execute_script(ANIMATING, el))
return el
driver.find_element(By.ID, "open-filters").click()
drawer = wait_for_animation_end(driver, (By.CSS_SELECTOR, ".filter-drawer"))
drawer.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
const ANIMATING = `
return arguments[0].getAnimations({ subtree: true }).some(a =>
a.playState === 'running' &&
a.effect && a.effect.getComputedTiming().iterations !== Infinity);`;
async function waitForAnimationEnd(driver, locator, timeout = 5000) {
const el = await driver.wait(until.elementLocated(locator), timeout);
await driver.wait(until.elementIsVisible(el), timeout);
await driver.wait(async () => !(await driver.executeScript(ANIMATING, el)), timeout, 'still animating');
return el;
}
await driver.findElement(By.id('open-filters')).click();
const drawer = await waitForAnimationEnd(driver, By.css('.filter-drawer'));
await drawer.findElement(By.css("button[type='submit']")).click();
const string Animating = """
return arguments[0].getAnimations({ subtree: true }).some(a =>
a.playState === 'running' &&
a.effect && a.effect.getComputedTiming().iterations !== Infinity);
""";
public static IWebElement WaitForAnimationEnd(IWebDriver driver, By locator, TimeSpan timeout)
{
var wait = new WebDriverWait(driver, timeout);
var el = wait.Until(d => d.FindElements(locator).FirstOrDefault(e => e.Displayed));
var js = (IJavaScriptExecutor)driver;
wait.Until(_ => !(bool)js.ExecuteScript(Animating, el));
return el;
}
driver.FindElement(By.Id("open-filters")).Click();
var drawer = WaitForAnimationEnd(driver, By.CssSelector(".filter-drawer"), TimeSpan.FromSeconds(5));
drawer.FindElement(By.CssSelector("button[type='submit']")).Click();

Fallback: Wait for a Stable Position

Animations driven by requestAnimationFrame loops or older libraries do not show up in getAnimations(). For those, wait until the element’s bounding box is the same on two consecutive polls:

Wait until the element stops moving
Selenium 3 & 4 Medium
public static void waitUntilStill(WebDriver driver, WebElement el, Duration timeout) {
Rectangle[] last = { null };
new WebDriverWait(driver, timeout)
.pollingEvery(Duration.ofMillis(100))
.until(d -> {
Rectangle now = el.getRect();
boolean still = now.equals(last[0]);
last[0] = now;
return still;
});
}
def wait_until_still(driver, el, timeout=5):
last = {"rect": None}
def still(_):
now = el.rect
same = now == last["rect"]
last["rect"] = now
return same
WebDriverWait(driver, timeout, poll_frequency=0.1).until(still)
async function waitUntilStill(driver, el, timeout = 5000) {
let last = null;
await driver.wait(async () => {
const now = JSON.stringify(await el.getRect());
const same = now === last;
last = now;
return same;
}, timeout, 'element kept moving', 100);
}
public static void WaitUntilStill(IWebDriver driver, IWebElement el, TimeSpan timeout)
{
(System.Drawing.Point, System.Drawing.Size)? last = null;
var wait = new WebDriverWait(driver, timeout) { PollingInterval = TimeSpan.FromMilliseconds(100) };
wait.Until(_ =>
{
var now = (el.Location, el.Size);
var same = now.Equals(last);
last = now;
return same;
});
}

Why It Works

getAnimations({ subtree: true }) returns every CSS animation, CSS transition and Web Animations API animation currently affecting the element or its children. Checking playState === 'running' tells you whether anything is still moving, regardless of duration, so the wait adapts automatically when designers change the timing. Filtering out iterations === Infinity stops a looping spinner inside the drawer from blocking the wait forever.

Gotchas

  • Disable animations in test environments if you can. A global CSS rule (*, *::before, *::after { transition: none !important; animation: none !important; }) injected in test builds, or honouring prefers-reduced-motion, removes this whole class of flakiness. Keep one or two tests with animations on.
  • Animate the right element. Often the container animates, not the button. Pass the drawer or modal root, with subtree: true, rather than the button itself.
  • Transitions that have not started yet. Right after the click, the transition might not have begun, so “no running animations” is briefly true. Wait for visibility first (as above), or for the open-state class, before checking animations.
  • The stability fallback needs two equal samples. With a 100 ms poll interval, a very slow easing at the end could look still for one interval. Increase the interval or require three equal samples for slow animations.

Learn the theory