Sub topic 14
Feature detection and fallbacks
Popovers are supported in current versions of all major browsers, but you may still meet older browsers, embedded web views, or locked-down corporate environments that lack them. This chapter covers how to detect support, what breaks when support is missing, and how to build a fallback that keeps the page usable. It assumes you know the popover attribute, popovertarget, showPopover(), and the :popover-open pseudo-class from earlier chapters. It also assumes you can write basic @supports rules.
What happens in an unsupported browser
A browser that does not know the popover attribute treats it as an unknown attribute and ignores it. Three things follow:
- The popover element is not hidden. Its content renders inline in the normal page flow, because the "hidden until opened" behavior comes from the browser's built-in stylesheet for
[popover]. - The invoker button does nothing.
popovertargetandpopovertargetactionare ignored. - Calls such as
panel.showPopover()throw aTypeError, because the method does not exist.
So the failure is not a missing feature. It is a visible layout change plus dead buttons. A good fallback handles both.
Your first decision is which behavior to accept without support. For some content, showing it inline is acceptable. A "help" paragraph that is always visible is a fine degradation. For a menu, it is not.
Detecting support
There are several ways to detect support. Each answers a slightly different question.
| Technique | What it tells you | Notes |
|---|---|---|
| `'popover' in HTMLElement.prototype` | The `popover` IDL property exists | Simple and synchronous |
| `typeof HTMLElement.prototype.showPopover === 'function'` | The JavaScript methods exist | Best check before calling methods |
| `@supports selector(:popover-open)` | CSS understands the pseudo-class | Use for CSS-only fallbacks |
| `matches(':popover-open')` inside `try`/`catch` | Pseudo-class parses at runtime | Throws `SyntaxError` when unsupported |
The property check from the earlier example works well as a default:
const supportsPopover =
typeof HTMLElement !== 'undefined' &&
Object.prototype.hasOwnProperty.call(HTMLElement.prototype, 'popover');
if (!supportsPopover) {
document.documentElement.classList.add('no-popover');
}The typeof HTMLElement guard keeps the code from throwing in environments with no DOM, such as server-side rendering or a test runner. Adding a class to the root element lets your CSS react to the result.
Why you should test the feature, not the browser
Do not parse the user agent string to guess support. User agent strings are unreliable and go stale. A browser can also ship the attribute while lacking a newer part of the feature. Test the exact thing you are about to use.
For example, the animation chapter used transition-behavior-style allow-discrete transitions on display and overlay. A browser can support popovers but not those transitions. In that case the popover still opens and closes correctly. It just closes without an exit animation. That is a graceful degradation and needs no fallback code. Reserve fallbacks for failures that break function.
CSS detection with @supports
CSS has its own feature query. The selector() function tests whether the browser can parse a selector:
@supports not selector(:popover-open) {
[popover] {
display: none;
}
[popover].is-open {
display: block;
}
}In a supporting browser, this block is skipped entirely and the native behavior applies. In an unsupported browser, the block hides every [popover] element and shows it only when a script adds the is-open class.
A selector-list gotcha
If a CSS selector list contains one selector the browser cannot parse, the whole rule is dropped. This breaks code like the following in an old browser:
/* Both selectors are lost if :popover-open is unknown. */
[popover]:popover-open,
.menu.is-open {
display: block;
}Write separate rules, or use :is()/:where(), which forgive invalid selectors in their arguments. Separate rules are the clearest choice:
[popover]:popover-open {
display: block;
}
.menu.is-open {
display: block;
}Building a script-based fallback
A fallback should do the minimum the native feature does:
- Open and close on invoker clicks, honoring
popovertargetaction. - Close an
autopopover on Escape and on outside clicks. - Keep
aria-expandedon the invoker in sync.
Here is a complete, small implementation. It runs only when native support is absent:
function setupPopoverFallback() {
const openPanels = new Set();
function setOpen(panel, invoker, open) {
panel.classList.toggle('is-open', open);
if (open) {
openPanels.add(panel);
} else {
openPanels.delete(panel);
}
if (invoker) {
invoker.setAttribute('aria-expanded', String(open));
}
}
document.querySelectorAll('[popovertarget]').forEach((invoker) => {
const panel = document.getElementById(
invoker.getAttribute('popovertarget')
);
if (!panel) return;
invoker.setAttribute('aria-expanded', 'false');
invoker.addEventListener('click', () => {
const action = invoker.getAttribute('popovertargetaction') || 'toggle';
const isOpen = panel.classList.contains('is-open');
if (action === 'show' || (action === 'toggle' && !isOpen)) {
setOpen(panel, invoker, true);
} else if (action === 'hide' || (action === 'toggle' && isOpen)) {
setOpen(panel, invoker, false);
}
});
});
document.addEventListener('keydown', (event) => {
if (event.key !== 'Escape') return;
openPanels.forEach((panel) => {
if (panel.getAttribute('popover') !== 'manual') {
setOpen(panel, null, false);
}
});
});
document.addEventListener('click', (event) => {
openPanels.forEach((panel) => {
const isAuto = panel.getAttribute('popover') !== 'manual';
const clickedInside = panel.contains(event.target);
const clickedInvoker = event.target.closest('[popovertarget]');
if (isAuto && !clickedInside && !clickedInvoker) {
setOpen(panel, null, false);
}
});
});
}
const supportsPopover =
typeof HTMLElement !== 'undefined' &&
Object.prototype.hasOwnProperty.call(HTMLElement.prototype, 'popover');
if (!supportsPopover) {
document.documentElement.classList.add('no-popover');
setupPopoverFallback();
}Pair it with CSS that recreates the native default look:
.no-popover [popover] {
display: none;
}
.no-popover [popover].is-open {
display: block;
position: fixed;
top: 20%;
left: 50%;
transform: translateX(-50%);
z-index: 1000;
padding: 1rem;
background: white;
border: 1px solid #888;
}This fallback has known limits:
- No top layer. The panel relies on
z-index, so an ancestor that creates a stacking context, oroverflow: hidden, can still clip or cover it. Position fixed escapes most clipping but not transforms on ancestors. - No stacking logic. Nested popovers do not close their ancestors correctly. The fallback treats every open panel independently.
- No focus handling beyond what the browser does by default.
If your design needs nested menus or complete behavior parity, a fallback this size is not enough.
Using a polyfill
A polyfill is a script that adds a missing feature. OddBird publishes a popover polyfill (@oddbird/popover-polyfill) that implements popover, popovertarget, and the JavaScript methods for older browsers. It also covers parts of the top-layer and light-dismiss behavior. Consult its documentation for the exact CSS and :popover-open handling it needs, because polyfills cannot add real browser pseudo-classes and typically use a class or attribute instead.
Choose between a polyfill and a handwritten fallback like this:
- Use a handwritten fallback when popovers are simple disclosure widgets and the unsupported audience is small.
- Use a polyfill when you rely on nesting, many popovers, or the full JavaScript API.
- Use neither when inline content is an acceptable degradation, as with a help note.
Guarding JavaScript calls
Code that calls the API directly must check first. Without the check, one unsupported call stops the rest of your script:
function openPanel(panel) {
if (typeof panel.showPopover === 'function') {
panel.showPopover();
} else {
panel.classList.add('is-open');
}
}Checking the method on the element, not on the global, is slightly safer. It also keeps the code correct if only part of the API is present.
The same applies to matches(':popover-open'). In a browser that does not know the pseudo-class, the call throws a SyntaxError. Wrap it:
function isOpen(panel) {
try {
return panel.matches(':popover-open');
} catch {
return panel.classList.contains('is-open');
}
}Common errors
- Detecting with
document.createElement('div').popover. For an unsupported property this returnsundefined, which works, but a supported one returns an empty string for a missing attribute ornull. Test withinorhasOwnProperty, not truthiness. - Forgetting the unsupported default is visible. Developers test only the supported path and never notice the popover content showing inline.
- Hiding content with
display: nonein all browsers. This hides it in supporting browsers too, where the native:popover-openrule needs to win. Scope hiding rules under.no-popoveror@supports not. - Mixing invalid selectors in one list, as shown earlier.
Exercise
A page uses a popover menu. In an old browser the menu text appears permanently below the button, and clicking the button does nothing. Name the cause, and write the check you would use before calling menu.showPopover().
Show answer
The browser ignores the unknown popover and popovertarget attributes, so the menu loses its "hidden until opened" default styling and the invoker has no behavior. Guard the call with if (typeof menu.showPopover === 'function') { menu.showPopover(); } else { menu.classList.add('is-open'); }, and hide the menu by default under .no-popover [popover] so it is not shown inline.
Exercise
Why does the rule [popover]:popover-open, .menu.is-open { display: block; } fail in a browser without popover support, and how do you fix it?
Show answer
The browser cannot parse :popover-open, so it discards the entire selector list, including .menu.is-open. Split it into two separate rules so the valid selector still applies.