How do I animate a popover opened with showPopover() without losing its exit transition?
Use :popover-open, @starting-style, and discrete transitions on display and overlay so a JavaScript-opened popover animates in and still remains visible long enough to animate out.
A popover that opens with showPopover() can still feel broken if the close motion is invisible. The browser is doing the state change, but CSS decides whether there is anything left to animate when the state flips back to hidden. The fix is not to add more script. It is to define both visual states, give the open state a starting frame, and keep the element rendered long enough for the exit transition to complete.
MDN’s Popover API guidance points to the pieces that matter: use the :popover-open pseudo-class for the shown state, @starting-style for the entry animation, and include display and overlay in the transition list with allow-discrete. With that setup, the popover can animate in and still remain observable while it animates out, instead of vanishing the moment the close call happens.
Why the popover looks fine going in but vanishes on the way out
The symptom is easy to describe and hard to diagnose if you look only at the JavaScript. A popover opened with showPopover() appears, but when you close it the element seems to disappear immediately instead of finishing the exit transition. The open motion may look smooth, which makes the close failure feel like a separate bug. It is not separate. It is the same state change seen from the other side.
The browser is doing what you asked in terms of state: the popover is shown, then hidden. The missing piece is visual continuity. A transition needs a start state, an end state, and enough time for the browser to keep painting the element while it moves between those states. If the hidden state removes the element from view too early, there is no visible exit to animate.
That is why the article question is specifically about showPopover(). The method is not the thing that “breaks” the transition. It simply makes the state change explicit. Once the browser owns the show and hide operation, CSS has to own the visual contract that keeps the popover renderable while the closing motion runs. If that contract is incomplete, the element can vanish at the exact moment you most need it to stay visible.
The useful mental model is that showing and hiding are not the same as entering and leaving the screen. The first pair is about browser state. The second pair is about paint and timing. A popover animation fails when those two layers are treated as if they were the same mechanism.
// This module provides a small, testable popover transition helper.
// It models the article's working idea: JavaScript should only guard state,
// while CSS supplies the transition configuration that keeps the popover
// visible long enough to animate out.
const REQUIRED_PROPERTIES = new Set(['opacity', 'transform', 'display', 'overlay']);
const DISCRETE_PROPERTIES = new Set(['display', 'overlay']);
export function buildPopoverTransition({ durationMs = 700, properties } = {}) {
if (!Number.isFinite(durationMs) || durationMs <= 0) {
throw new RangeError('durationMs must be a positive finite number');
}
const selected = properties ?? ['opacity', 'transform', 'display', 'overlay'];
if (!Array.isArray(selected) || selected.some((property) => !REQUIRED_PROPERTIES.has(property))) {
throw new TypeError('properties must contain only supported popover transition properties');
}
for (const required of REQUIRED_PROPERTIES) {
if (!selected.includes(required)) {
throw new Error(`Missing required popover transition property: ${required}`);
}
}
return Object.freeze({
durationMs,
properties: Object.freeze(
selected.map((property) => Object.freeze({
property,
allowDiscrete: DISCRETE_PROPERTIES.has(property),
})),
),
});
}
export const popoverAnimationCss = `
[popover] {
opacity: 0;
transform: scaleX(0);
transition:
opacity 700ms,
transform 700ms,
display 700ms allow-discrete,
overlay 700ms allow-discrete;
}
[popover]:popover-open {
opacity: 1;
transform: scaleX(1);
}
@starting-style {
[popover]:popover-open {
opacity: 0;
transform: scaleX(0);
}
}
`;
export function createPopoverCommands(popover) {
if (
!popover ||
typeof popover.matches !== 'function' ||
typeof popover.showPopover !== 'function' ||
typeof popover.hidePopover !== 'function'
) {
throw new TypeError('popover must provide matches(), showPopover(), and hidePopover()');
}
function isOpen() {
return popover.matches(':popover-open');
}
return Object.freeze({
isOpen,
open() {
if (isOpen()) return 'already-open';
popover.showPopover();
return 'opened';
},
close() {
if (!isOpen()) return 'already-closed';
popover.hidePopover();
return 'closed';
},
});
}
showPopover() changes state, not animation
MDN describes showPopover() as the method that shows a valid popover element by adding it to the top layer. It also notes the sequence around the call: beforetoggle fires, the popover shows, and then toggle fires. That sequence is useful because it tells you exactly where script ends and browser behavior begins. showPopover() does not create a polished animation by itself. It creates the state change that the animation can respond to.
That difference matters because a lot of debugging starts with the wrong question: “Why is my animation not working?” The better question is: “What state does the browser expose while the element is entering and leaving?” In a popover flow, the state is observable through :popover-open. If you treat that pseudo-class as the one source of truth, your CSS can stay aligned with the actual browser state rather than with a separate boolean that might drift.
This is also why using toggle logic in script is not the answer by itself. JavaScript can choose when to show or hide, but it cannot replace the browser’s rendering rules. If the element is already open and your code calls showPopover() again, or if it is already closed and you call hidePopover() again, you have not solved animation timing. You have only introduced another place where the browser can reject or short-circuit the request.
So the first step is conceptual, not cosmetic: accept that showPopover() is a state transition API. The animation itself still belongs in CSS, and the CSS has to be written in a way that respects the browser’s open and closed states.
The open and closed states need distinct style rules
The reliable pattern starts by giving each state a clear role. The closed selector, [popover], defines the hidden end state: low opacity and a compressed transform. The open selector, [popover]:popover-open, defines the visible state: full opacity and the full transform. Once those two ends are explicit, the browser can interpolate between them in both directions.
This is where it is easy to write something that looks reasonable but is incomplete. If you only style the open state, the browser may know what the popover should look like when it is visible, but it still does not know what frame to animate from when the popover first appears. If you only style the closed state, the browser may know the exit target, but it still does not know how to begin the entry cleanly. The article’s fix depends on both ends being present.
MDN’s guidance adds @starting-style for exactly that reason. Starting styles supply the initial frame for the entry animation even though the open selector already exists. That makes the first visible frame deterministic instead of implicit. The browser can then animate from the starting values into the [popover]:popover-open values without inventing its own entry state.
The result is more than a fade. It is a complete state map: hidden, entering, open, leaving. When the states are described that way, the stylesheet does not merely decorate the popover; it expresses the movement contract that the browser should preserve while the element changes visibility.
display and overlay preserve the exit transition
The crucial detail in MDN’s animation example is not the scale or opacity timing. It is the inclusion of display and overlay in the transition list with allow-discrete. That is what keeps the popover alive long enough to be seen while it is leaving. Without those properties, the browser can effectively stop rendering the element before the closing transition has time to finish.
This is the part that most directly answers the title question. A popover can lose its exit transition even when the visual properties are correct if the browser is allowed to remove the element from the visible rendering path too early. display controls whether the element remains rendered; overlay controls whether it stays in the top layer long enough to complete the transition. The animation only survives if both are accounted for in the transition setup.
It helps to think of this as a separation between style and lifecycle. opacity and transform describe how the panel should look while it moves. display and overlay describe whether the browser still keeps it in a state where that movement can be observed. If you only animate the visible properties, you are assuming the element will continue to exist long enough for those changes to matter. That assumption is exactly what fails in a disappearing popover.
That is also why the article does not recommend a script delay as the primary fix. Waiting in JavaScript can be a workaround, but it does not explain the browser’s lifecycle contract. The documented CSS transition setup does. It tells the browser to keep the popover rendered through the exit so the closing motion can actually be seen.
JavaScript should guard state rather than force toggles
Once the CSS contract is correct, the JavaScript can stay simple. The script’s job is not to choreograph frames; it is to avoid redundant or invalid state changes. MDN recommends checking :popover-open before calling showPopover() or hidePopover(). That keeps the code from asking the browser to open an already-open popover or close an already-closed one.
That guard matters because duplicate calls create noise right where you need clarity. If the state check is wrong, the animation bug becomes harder to read: was the popover invisible because the CSS transition failed, or because the browser rejected a redundant show or hide? By using the browser’s own state test, you remove that ambiguity and make the remaining bug much easier to reason about.
The same idea applies to event handling. If a button opens the popover, the script should not also pretend to be the animation engine. A useful handler can decide whether the popover should open or close, but the styling still owns how the motion appears. That division of responsibility is what keeps the implementation maintainable when the animation evolves later.
In other words, the browser already knows how to tell you whether the popover is open. Your script should ask that question and then stop. The CSS can then do the visible work without being second-guessed by code that tries to guess the rendering state from unrelated application flags.
SourcesMDN: HTMLElement.showPopover() (opens a new tab)MDN: Using the Popover API (opens a new tab)
What the fix solves and what it does not
The repair solves one narrow but important problem: a popover opened with showPopover() can animate in and still animate out visibly when the stylesheet defines both states, provides a starting style, and keeps display and overlay in the transition set with allow-discrete. That is the outcome the reader can actually verify in the browser: the closing motion remains visible instead of collapsing into an instant disappearance.
There are limits. This pattern does not turn a popover into a modal dialog, and it does not solve focus management by itself. It also does not mean every browser will behave identically in every timing detail. The claim here is narrower and stronger at the same time: the documented transition setup preserves the exit animation boundary that would otherwise be lost when the popover is hidden.
The same limits apply if you change the close behavior. If your code removes the element from the DOM instead of hiding the popover, you have changed the problem. The browser cannot animate an element that no longer exists. Likewise, if you omit @starting-style, the entry can become less deterministic even if the exit still works in some cases. Each omitted piece changes the contract in a different way.
That is why the article’s answer is not “add animation to showPopover().” The answer is to let showPopover() handle state, let CSS handle the visible transition, and use the documented discrete-transition properties so the exit state remains observable long enough to finish the motion. Once those responsibilities are separated, the popover behaves like a single interaction instead of two unrelated flashes.
import assert from 'node:assert/strict';
import test from 'node:test';
import { buildPopoverTransition, createPopoverCommands, popoverAnimationCss } from './main.mjs';
function makePopover(initiallyOpen = false) {
let open = initiallyOpen;
const calls = [];
return {
calls,
matches(selector) {
assert.equal(selector, ':popover-open');
return open;
},
showPopover() {
calls.push('showPopover');
if (open) throw new Error('showPopover called while already open');
open = true;
},
hidePopover() {
calls.push('hidePopover');
if (!open) throw new Error('hidePopover called while already closed');
open = false;
},
};
}
test('open() reaches showPopover() and transitions an initially hidden popover to open', () => {
const popover = makePopover(false);
const commands = createPopoverCommands(popover);
assert.equal(commands.open(), 'opened');
assert.deepEqual(popover.calls, ['showPopover']);
assert.equal(commands.isOpen(), true);
});
test('open() has an already-open boundary and does not call showPopover() twice', () => {
const popover = makePopover(true);
const commands = createPopoverCommands(popover);
assert.equal(commands.open(), 'already-open');
assert.deepEqual(popover.calls, []);
assert.equal(commands.isOpen(), true);
});
test('close() has an already-closed boundary and does not call hidePopover()', () => {
const popover = makePopover(false);
const commands = createPopoverCommands(popover);
assert.equal(commands.close(), 'already-closed');
assert.deepEqual(popover.calls, []);
assert.equal(commands.isOpen(), false);
});
test('transition configuration requires display and overlay so the exit branch is preserved', () => {
assert.throws(
() => buildPopoverTransition({ properties: ['opacity', 'transform', 'overlay'] }),
/Missing required popover transition property: display/,
);
});
test('default transition configuration includes the discrete properties and CSS mentions @starting-style', () => {
const transition = buildPopoverTransition();
assert.deepEqual(
transition.properties,
[
{ property: 'opacity', allowDiscrete: false },
{ property: 'transform', allowDiscrete: false },
{ property: 'display', allowDiscrete: true },
{ property: 'overlay', allowDiscrete: true },
],
);
assert.match(popoverAnimationCss, /@starting-style/);
});
SourcesMDN: Using the Popover API (opens a new tab)MDN: HTMLElement.showPopover() (opens a new tab)


