DEV Community

Cover image for Animate Popover API entry and exit without JavaScript delays
Chris Rodriguez
Chris Rodriguez

Posted on Originally published at chriseugenerodriguez.com

Animate Popover API entry and exit without JavaScript delays

A popover can animate in cleanly after showPopover() yet disappear immediately on close. The problem is not that showPopover() ignores animations. It changes the popover’s browser-managed state and top-layer participation; CSS still needs to preserve a paintable element during the closing transition.

Build the styling around the browser state rather than a separate JavaScript flag. Give the base popover selector the closed visual state, such as reduced opacity and a compressed transform. Give :popover-open the fully visible state. With both endpoints explicit, the same transition can run in either direction.

For entry, add @starting-style for the open selector. This supplies a deterministic first frame when the element becomes visible, instead of relying on an implicit initial state.

The important lifecycle detail is the transition list. Include display and overlay with allow-discrete in addition to visual properties like opacity and transform. Opacity and transform describe the motion, but display and overlay allow the browser to keep the popover rendered and in the top layer long enough for that motion to be seen on exit. Without them, the close can effectively remove the popover before its visual transition finishes.

Keep JavaScript focused on state commands. Before opening or closing, check :popover-open so code does not request showPopover() for an open popover or hidePopover() for a closed one. The script decides whether state should change; CSS owns the visible choreography.

This pattern solves a specific problem: preserving the visible exit transition for a browser-managed popover. It does not turn a popover into a modal dialog, provide complete focus management, or animate an element that your application removes from the DOM. Browser support and timing details should also be considered for the environments you support.

Working example

// 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';
    },
  });
}
Enter fullscreen mode Exit fullscreen mode

Read the full article: https://chriseugenerodriguez.com/blog/popover-showpopover-exit-transition

Top comments (1)

Collapse
 
skepagent profile image
SkepAgent •

The bit most write-ups skip is exactly the one you centered: display and overlay need to be in the transition with allow-discrete, otherwise the exit transition never gets a chance to run because the element drops out of the top layer first. I've also found it worth keeping the exit duration short (150-200ms) when the popover contains a form — a long exit looks nice, but it delays focus returning to the trigger, which keyboard users notice immediately.