Dialogs and popovers in components
Use dialogs and popovers in web components: showModal() in a shadow root, closedby, popover values, custom commands, inert, and where focus goes.
- 01Open a dialog from a shadow rootUse
showModal()inside a component, style its::backdrop, chooseclosedby, and readreturnValue. - 02Pick the right popoverChoose
auto,hint, ormanual, and know where focus goes when each one opens and closes. - 03Drive them with buttonsWire
commandandcommandforinside one tree, and give your own element custom--commandsa page can send.
How do you put a dialog in a web component?
Asha has three teas in her cart at Leaf and Kettle. She presses Checkout. A box asks: "Place your order?" Meena uses the keyboard and a screen reader. She opens the same box, then presses Esc. Where does her focus land now? And the box lives inside the cart's shadow root. Does that change anything?
Put a <dialog> in the component's shadow root and open it with showModal(). The browser draws it above the whole page, blocks the rest of the page, and moves focus inside. When it closes, focus goes back to the button that opened it. You write no focus code at all. Here is a small checkout component that does it:
<tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> const root = document.querySelector("tea-checkout").shadowRoot; root.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>- Line 1 is the tag. Line 2 loads the component from the tea-checkout.js tab.
- Lines 4 and 5 print each focus move inside the shadow root.
Here is the tea-checkout.js tab:
class TeaCheckout extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>dialog::backdrop { background: rgb(0 60 30 / 0.5); }</style>
<button id="open">Checkout</button>
<dialog id="confirm" aria-labelledby="ask">
<p id="ask">Place your order?</p>
<button id="keep">Keep shopping</button>
</dialog>`;
const dialog = this.shadowRoot.getElementById("confirm");
this.shadowRoot.getElementById("open").addEventListener("click", () => dialog.showModal());
this.shadowRoot.getElementById("keep").addEventListener("click", () => dialog.close());
}
}
customElements.define("tea-checkout", TeaCheckout);- Line 4 attaches the shadow root. Everything up to line 10 goes inside it.
- Line 5 styles the dark layer behind the dialog. The next section explains it.
- Lines 7 to 10 are the dialog. Its
aria-labelledbypoints at the question on line 8, so the question names the dialog. - Line 12 opens the dialog when Checkout is clicked. Line 13 closes it from Keep shopping.
Click in the result and press Tab. It prints Focus: Checkout. Press Enter: Focus: Keep shopping. The dialog opened, and focus moved inside. Now press Esc: Focus: Checkout. Focus came back.
The shop phone rings while Ravi is serving Asha. He picks it up and puts a sign on the counter: Back in a minute. Nobody can be served until the call ends. When he hangs up, he turns back to Asha, right where he left off.
- In real life: Ravi picking up the phone
- In JavaScript:
showModal() - In real life: The call itself
- In JavaScript: The open dialog
- In real life: The sign that says Back in a minute
- In JavaScript: The rest of the page, which can't be used
- In real life: Hanging up and turning back to Asha
- In JavaScript: Closing, and focus going back to the button
A dialog or popover inside a component works the way it does on the page. showModal() lifts the dialog above everything, blocks the rest, and hands focus back when it closes. Buttons open and close them with command and commandfor inside one tree. Custom --commands let the page talk to your element.
Why it matters: the browser does the hard parts of an accessible dialog. A shadow root doesn't take any of them away.
What does showModal() do inside a shadow root?
A <dialog> is a box for a short task, like a question. show() opens it as a non-modal dialog, and the page stays usable. showModal() opens it as a modal dialog. A modal dialog must be answered before anything else. The HTML Standard gives showModal() four jobs:
- It puts the dialog in the top layer: a layer the browser draws above every other box on the page.
- It draws a
::backdropbehind the dialog. That's a layer that covers the rest of the page. - It makes everything outside the dialog inert. Inert content can't be clicked, focused, or found by a screen reader.
- It remembers what had focus, and moves focus into the dialog.
Where the dialog sits in the tree doesn't matter. Here the checkout component sits in an aside that's only 40 pixels tall. The aside hides anything that sticks out of it:
<aside style="height: 40px; overflow: hidden; border: 2px solid seagreen"> <tea-checkout></tea-checkout></aside><script src="tea-checkout.js"></script><script> const dialog = document.querySelector("tea-checkout").shadowRoot.querySelector("dialog"); dialog.addEventListener("toggle", (event) => { if (event.newState === "closed") return; console.log("Modal:", dialog.matches(":modal")); console.log("Backdrop:", getComputedStyle(dialog, "::backdrop").backgroundColor); });</script>- Line 1 is the aside: 40 pixels tall, with
overflow: hidden. - Line 6 finds the dialog in the component's shadow root. The tea-checkout.js tab is the same as before.
- Lines 7 to 11 run when the dialog opens or closes, and line 8 skips the close. Line 9 prints whether the dialog matches
:modal, a selector for an open modal dialog. Line 10 prints the color of its backdrop.
Click Checkout. It prints Modal: true and Backdrop: rgba(0, 60, 30, 0.5). The dialog shows in full, over the whole result, and the page behind it turns dark green. The aside didn't cut it off.
Look at line 5 of the tea-checkout.js tab. dialog::backdrop is a rule in the shadow root's own <style>. The backdrop belongs to the dialog, so the shadow root's styles reach it, like any rule in lesson 11.1.
showModal() draws it in the top layer, above the whole page, with its ::backdrop behind it.The top layer is also why you don't move a dialog out of a component to show it. React developers often use a portal to draw a modal at the end of the page, away from overflow and z-index. The React course's portals lesson shows that a dialog opened with showModal() needs no portal. One warning: lesson 3.5 showed that moving an element with append() closes an open modal dialog or popover inside it. moveBefore() keeps it open.
Why it matters: a component can keep its dialog private, in its own shadow root, and still show it above everything.
How do you close a dialog element?
There are four ways to close a dialog:
- your own button calls
close(); - a close request: Esc on a keyboard, or the back gesture on a phone;
- a click outside the dialog, on its backdrop;
- a form inside the dialog with
method="dialog"is sent.
A close request first fires a cancel event. Then the dialog closes and fires close. The closedby attribute says which of these a person may use. Try its three values:
<tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> const dialog = document.querySelector("tea-checkout").shadowRoot.querySelector("dialog"); dialog.addEventListener("toggle", (event) => { if (event.newState === "open") console.log("closedBy:", dialog.closedBy); }); dialog.addEventListener("cancel", () => console.log("cancel")); dialog.addEventListener("close", () => console.log("close"));</script>A dialog opened with showModal() acts as closedby="closerequest". Escape fires cancel, then close. A click on the backdrop does nothing.
- Line 6 prints
closedBywhen the dialog opens. That property tells you which rule is in force. - Lines 8 and 9 print each
cancelandcloseevent.
- No closedby:
closedBy: closerequest. Esc printscancel, thenclose. A click outside does nothing. - closedby="any": Esc and a click outside both print
cancel, thenclose. - closedby="none": Esc and a click outside do nothing. Only Keep shopping closes it.
So a modal dialog closes on Esc unless you say otherwise. A dialog opened with show() starts at none. Use none rarely: the APG lists Esc as the key that closes a dialog. Chrome and Firefox support closedby. Safari doesn't yet, so Esc still closes a modal dialog there, and a click outside doesn't.
Reading returnValue
close() can take a string, like close("order"). The dialog keeps it in returnValue, so the close listener knows which button was pressed. But a close with no value changes nothing:
<button id="open">Checkout</button><dialog id="confirm" aria-label="Place your order?"> <button id="order">Place order</button> <button id="later">Not now</button></dialog><script> const dialog = document.getElementById("confirm"); document.getElementById("open").addEventListener("click", () => dialog.showModal()); document.getElementById("order").addEventListener("click", () => dialog.close("order")); document.getElementById("later").addEventListener("click", () => dialog.close()); dialog.addEventListener("close", () => console.log("returnValue:", dialog.returnValue));</script>- Line 9 closes with
"order". Line 10 closes with no value. - Line 11 prints
returnValueeach time the dialog closes.
Click Checkout, then Place order: returnValue: order. Click Checkout again, then Not now. It prints returnValue: order again. The old value stayed. So set returnValue back to an empty string each time the dialog opens. The kit's cart does that in the practical section.
Asking before you close
requestClose() closes a dialog the way Esc does. It fires cancel first, and a listener can stop it with preventDefault(). It works even with closedby="none":
<button id="open">Checkout</button><dialog id="confirm" aria-label="Notes for the shop"> <textarea aria-label="Notes"></textarea> <button id="later">Later</button></dialog><script> const dialog = document.getElementById("confirm"); document.getElementById("open").addEventListener("click", () => dialog.showModal()); document.getElementById("later").addEventListener("click", () => dialog.requestClose()); dialog.addEventListener("cancel", (event) => { if (dialog.querySelector("textarea").value) event.preventDefault(); console.log(event.defaultPrevented ? "Kept open: you wrote a note" : "Closing"); });</script>- Line 9 calls
requestClose()from Later. - Lines 10 to 13 run on
cancel. Line 11 stops the close when the box holds a note. Line 12 prints what happened.
Click Checkout, then Later: Closing. Open it again, type a note, and click Later: Kept open: you wrote a note. The note is safe. Esc fires the same cancel event, so one listener handles both.
Why it matters: closedby picks the ways out, returnValue says which way was taken, and requestClose() lets you ask first.
Where does focus go when a dialog opens and closes?
Focus is the spot where key presses land, as lesson 9.3 showed. The APG's dialog pattern has two rules for it:
- When a dialog opens, focus moves inside it. Usually that's the first element that can take focus. Before a step you can't undo, like a purchase, pick the least destructive button. When there's a lot to read, start on a heading with
tabindex="-1". - When it closes, focus goes back to the element that opened it.
Here is how the browser picks where focus starts. An element with the autofocus attribute gets it. Without one, the first element inside that can take focus wins. Try three choices:
<tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> const root = document.querySelector("tea-checkout").shadowRoot; root.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>The browser looks for the first element inside the dialog that can take focus. A heading can't, so Place order wins.
- The page is the same as the overview's. In the tea-checkout.js tab, line 8 is a heading.
- Lines 9 and 10 are Place order, then Keep shopping.
- No autofocus:
Focus: Place order. One stray Enter would buy the tea. - autofocus on Keep shopping:
Focus: Keep shopping. This is the safe start for a purchase. - autofocus on the heading:
Focus: Place your order?. A screen reader starts at the top.
The second rule needs no code. When showModal() runs, the dialog remembers what had focus. The HTML Standard calls it the previously focused element. When the dialog closes, focus goes back there. The overview showed it: Esc printed Focus: Checkout.
The remembered element can live in any tree. In the custom commands section, a button on the page opens a dialog in a shadow root. When the dialog closes, focus lands on that page button again.
Meena is reading a tea guide. It sends her to a map at the back. She keeps a finger on her line, looks at the map, then flips back to her finger. She doesn't have to find her place again.
- In real life: The line you were reading
- In JavaScript: The element with focus
- In real life: Your finger on that line
- In JavaScript: The previously focused element
- In real life: The map at the back of the book
- In JavaScript: The dialog
- In real life: Flipping back to your finger
- In JavaScript: Focus going back when the dialog closes
One more case goes wrong if you don't plan for it. What if the opener is gone, or disabled, when the dialog closes? The APG says to move focus somewhere that makes sense. The kit's cart does this after an order.
For focus inside a component, lesson 14.1 showed delegatesFocus. For Tab and Shift+Tab in general, see Keyboard and focus on the JavaScript path. Why it matters: a keyboard user never loses their place, and you choose where they start.
What do popover auto, hint, and manual do?
Not every box should block the page. A menu, a tip, or a note should let people keep shopping. That's a popover: an element with the popover attribute. It stays hidden until it's shown, then appears in the top layer. It isn't modal: the page stays usable. Here is one inside a shadow root:
<tea-tips></tea-tips><p>Click outside the tips to close them, or press Esc.</p><script src="tea-tips.js"></script>Line 1 places the tag, and line 3 loads it. Here is the tea-tips.js tab:
class TeaTips extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>:popover-open { border: 2px solid seagreen; }</style>
<button popovertarget="tips">Brewing tips</button>
<p id="tips" popover>Use water at 80 degrees for green tea.</p>`;
const tips = this.shadowRoot.getElementById("tips");
tips.addEventListener("beforetoggle", (event) => console.log("beforetoggle:", event.newState));
tips.addEventListener("toggle", (event) => console.log("toggle:", event.newState));
}
}
customElements.define("tea-tips", TeaTips);- Line 6 is the button. Its
popovertargetnames the popover's id. - Line 7 is the popover: a paragraph with
popover. - Line 5 styles it while it's open.
:popover-openmatches a popover that's showing. - Lines 9 and 10 print two events.
beforetogglefires before it opens or closes.togglefires after.
Click Brewing tips: beforetoggle: open, then toggle: open. Click outside the tips: the same two lines with closed. Open them again and press Esc: they close too. Closing on a click outside or on Esc is called light dismiss. A listener can call preventDefault() on beforetoggle to stop a popover opening.
A plain popover means popover="auto". The attribute has three values, which the HTML Standard defines:
auto: light dismiss. Opening one closes the other auto popovers, unless it's nested in one.hint: light dismiss too. It closes other hints, but never an auto popover. It's made for tips that show on hover or focus.manual: no light dismiss, and it closes nothing. It stays until your code or a button closes it.
A popover is nested when it sits inside another popover. It's nested too when the button that names it, with popovertarget or commandfor, sits inside one. See the difference with an open menu and a tip:
<button popovertarget="menu">Menu</button><div id="menu" popover> <p>Sencha, Mint, Oolong</p> <button id="help">What is Oolong?</button></div><p id="tip" popover="hint">A tea between green and black.</p><script> const tip = document.getElementById("tip"); document.getElementById("help").addEventListener("mouseenter", () => tip.showPopover()); document.getElementById("help").addEventListener("focus", () => tip.showPopover()); for (const popover of document.querySelectorAll("[popover]")) { popover.addEventListener("toggle", (event) => console.log(popover.id, event.newState)); }</script>A hint popover doesn't close auto popovers. The menu stays open under it, and a click outside closes both.
- Lines 2 to 5 are the menu, an auto popover. Line 6 is the tip.
- Lines 9 and 10 open the tip from script, when the pointer enters its button or the button gets focus. No
popovertargetnames the tip, so it isn't nested. Line 12 prints every toggle.
- hint:
menu open,tip open. The menu stays. A click outside closes both. - auto:
menu open,menu closed,tip open. The tip closes the menu. - manual:
menu open,tip open. A click outside closes only the menu.
auto tip closes the menu. A hint or auto tip closes on a click outside or Esc. A manual tip stays until you close it.At a tea tasting, a server holds out a tray. Wave it away, or ask for another tray, and it goes. A small tip card can sit on the tray without taking it away. The price board on the wall stays up until the staff take it down.
- In real life: A tasting tray held out to you
- In JavaScript:
popover="auto" - In real life: Waving the tray away
- In JavaScript: Light dismiss: a click outside or Esc
- In real life: A small card with a tip, set on the tray
- In JavaScript:
popover="hint" - In real life: The price board on the wall
- In JavaScript:
popover="manual"
Popovers and focus
A popover handles focus more gently than a modal dialog:
- Opening it leaves focus on the button, unless something inside has
autofocus. - The next Tab from that button goes into the popover, wherever it is in the page.
- When an
autoorhintpopover closes with focus inside, focus goes back to the button. - A
manualpopover doesn't do that. Focus is lost, so move it yourself.
The same rules hold in a shadow root, with one limit. A popovertarget id only works in the button's own tree, as lesson 13.3 showed. That's why tea-tips keeps both in one shadow root. Adobe's shadow DOM support tracker also notes that Safari fails some focus tests for popovers inside shadow roots. So test focus there with the keyboard.
Safari doesn't support hint yet. A browser that doesn't know a value treats it as manual, so there the tip simply stays open. Chrome also has interestfor, which opens a popover on hover or focus with no script. Only Chrome supports it. Why it matters: pick the value by how the box should close, and your tips, menus, and notes behave the way people expect.
What are the command and commandfor attributes?
Every dialog so far needed a click listener. Invoker commands remove them. You give a button two attributes:
commandfor: the id of the element to control.command: what to do to it.
Here is tea-checkout again, with commands and no listeners at all:
class TeaCheckout extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = `
<style>dialog::backdrop { background: rgb(0 60 30 / 0.5); }</style>
<button commandfor="confirm" command="show-modal">Checkout</button>
<dialog id="confirm" aria-labelledby="ask">
<p id="ask">Place your order?</p>
<button commandfor="confirm" command="close" value="keep">Keep shopping</button>
<button commandfor="confirm" command="close" value="order">Place order</button>
</dialog>`;
}
}
customElements.define("tea-checkout", TeaCheckout);- Line 6: Checkout sends
show-modalto the dialog with the idconfirm. - Lines 9 and 10 send
close. Each button'svaluebecomes the dialog'sreturnValue.
<tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> const dialog = document.querySelector("tea-checkout").shadowRoot.querySelector("dialog"); dialog.addEventListener("command", (event) => console.log("command:", event.command)); dialog.addEventListener("close", () => console.log("returnValue:", dialog.returnValue));</script>Line 5 prints each command event, and line 6 prints returnValue. Click Checkout: command: show-modal. Click Place order: command: close, then returnValue: order. Focus still moves in and back, as before.
Before it acts, the browser fires a command event on the target. Calling preventDefault() on it stops the action. Here are the built-in commands, from MDN:
- for a dialog:
show-modal,close, andrequest-close, which callsrequestClose(); - for a popover:
show-popover,hide-popover, andtoggle-popover.
popovertarget is the older, popover-only way. Chrome's announcement says command and commandfor replace it. A toggle-popover button also tells screen readers whether its popover is expanded, with no ARIA from you.
The shop has one remote for the TV and the music. You pick a device, then press a button. Power and volume work on every device. A few spare buttons do whatever you program them to do.
- In real life: Choosing which device the remote talks to
- In HTML:
commandfor - In real life: The power and volume buttons
- In HTML: Built-in commands, like
show-modal - In real life: A button you program yourself
- In HTML: A custom command, like
--clear
Commands and shadow roots
commandfor is an id reference, so lesson 13.3's rule applies. The id is looked up in the button's own tree. That's why tea-checkout keeps its buttons and its dialog in one shadow root. A page button with commandfor="confirm" finds nothing. In script, commandForElement can point out of a shadow root, but not into one. Reference Target, from the same lesson, lets a host pass references on. Only Chrome turns it on by default. Eric Meyer lists commandfor and popovertarget among the attributes it fixes. The next section shows a fix that works everywhere.
One trap: a button inside a <form> with no type is usually a submit button. With commandfor, the browser can't tell which you meant, so the button does nothing. Give it type="button". Why it matters: buttons open and close dialogs and popovers with no listeners, and the browser keeps their states right.
How do you give a web component custom commands?
A command that starts with two dashes, like --add, is a custom command. The HTML Standard says the browser does only one thing with it. It fires command on the target. Your element listens, and does the work. Here is a cup counter with two custom commands:
class TeaCounter extends HTMLElement {
#cups = 0;
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = "<p>Cups: <output>0</output></p>";
this.addEventListener("command", (event) => {
if (event.command === "--add") this.#cups += 1;
else if (event.command === "--clear") this.#cups = 0;
else return;
this.shadowRoot.querySelector("output").value = this.#cups;
console.log(`${event.command} from ${event.source.localName}. Cups: ${this.#cups}`);
});
}
}
customElements.define("tea-counter", TeaCounter);- Line 7 listens for
commandon the element itself. - Lines 8 and 9 handle
--addand--clear. Line 10 ignores anything else. - Line 12 prints the command, the tag of
event.source, and the count. MDN sayssourceis the button that sent it.
<button commandfor="cups" command="--add">Add a cup</button><button commandfor="cups" command="--clear">Clear</button><tea-counter id="cups"></tea-counter><script src="tea-counter.js"></script><script> document.addEventListener("command", () => console.log("The document heard a command"));</script>Lines 1 and 2 name the counter's id, cups. Click Add a cup twice, then Clear. It prints --add from button. Cups: 1, then Cups: 2, then --clear from button. Cups: 0.
Look at what never prints: line 6's The document heard a command. The command event doesn't bubble, so only the target hears it. Chrome's guide says the same: listen on the target.
command on the host, and the host's listener empties the list inside its shadow root.This is the fix the last section promised. The page's button names the host, whose id is in the page. The host gets the command and does the work inside its own shadow root. No reference crosses a boundary. Try four buttons:
<button commandfor="cups" command="--add">Add a cup</button><tea-counter id="cups"></tea-counter><script src="tea-counter.js"></script>The value starts with two dashes, so the browser fires command on the counter, and its listener adds a cup.
- --add:
--add from button. Cups: 1. - add: nothing. Without the dashes, it's not a command at all.
- show-modal: nothing. That command only exists for dialogs.
- Inside a form: nothing. Chrome's DevTools console says the button needs
type="button".
The two dashes are the same mark that CSS custom properties start with. They make a command easy to tell apart from the built-in ones.
Where event.source points
A button inside a shadow root can point out at the page with commandForElement. Then whose button is source? Here a toolbar component sends --add to the page's counter:
class TeaToolbar extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" }).innerHTML = '<button command="--add">Add a cup</button>';
}
connectedCallback() {
const target = document.getElementById(this.getAttribute("for"));
this.shadowRoot.querySelector("button").commandForElement = target;
}
}
customElements.define("tea-toolbar", TeaToolbar);- Line 4 is the button, with a
commandbut nocommandfor. - Lines 8 and 9 find the element named by the host's
forattribute, and set the button'scommandForElementto it.
<tea-toolbar for="cups"></tea-toolbar><tea-counter id="cups"></tea-counter><script src="tea-counter.js"></script><script src="tea-toolbar.js"></script>Line 1 is the toolbar, and its for names the counter on line 2. Click Add a cup: --add from tea-toolbar. Cups: 1. The counter saw the toolbar, not its button. The HTML Standard retargets source to the host, as lesson 9.1 showed for an event's target. The toolbar's insides stay private. For events you dispatch yourself, see lesson 5.3.
Why it matters: a custom command is a public, written-down way for a page to drive your element, with no script on the page.
What does the inert attribute do?
inert is an attribute that switches part of a page off. MDN lists what an inert element and everything inside it lose:
- clicks do nothing, and it can't take focus;
- find in page skips its text, and you can't select it;
- screen readers can't find it.
Everything inside means the flat tree, from lesson 13.1. So buttons in a component's shadow root are switched off too:
<section inert> <tea-card name="Sencha" price="4.50"></tea-card> <button>Shop teas</button></section><button>Help</button><script type="module" src="tea-kit/index.js"></script><script> for (const button of document.querySelectorAll("button")) { button.addEventListener("click", () => console.log("Click:", button.textContent)); } document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>- Line 1 makes the section inert. Line 2 is a kit tea card, with buttons in its shadow root. Line 3 is a page button.
- Line 5 is outside the section.
- Lines 8 to 10 print each click on a page button. Line 11 prints each focus move.
Click Shop teas, or the card's Add button: nothing. Click in the result and press Tab: Focus: Help. Tab skipped the whole section, the card's buttons included. Click Help: Click: Help.
Leaf and Kettle closes its upstairs room with a rope. Customers can see the stairs, but they can't go up. Nothing up there can be reached, not even a cupboard in a back room. A sign on the rope says why.
- In real life: The rope at the foot of the stairs
- In JavaScript: The
inertattribute - In real life: Every room upstairs, cupboards too
- In JavaScript: The element and its whole flat tree
- In real life: A sign on the rope
- In JavaScript: A visible hint that the part is switched off
You don't need inert for a modal dialog. The HTML Standard says that while one is open, every node except the dialog and its flat tree becomes inert. That's why the overview never needed a trap. Here is a page with a heading, a Shop teas button, and the commands version of tea-checkout:
<h1>Leaf and Kettle</h1><button>Shop teas</button><tea-checkout></tea-checkout><script src="tea-checkout.js"></script>Lines 1 and 2 are a heading and a page button. Line 3 is the checkout component, and line 4 loads it. Click Checkout, then read the tree:
dialog "Place your order?", modal
button "Keep shopping", focused
button "Place order"Before the click, the tree listed the heading and both buttons. Now it holds only the dialog. The heading and Shop teas are gone for screen readers. For more on reading this tree, see lesson 14.3.
So when do you set inert yourself? When part of the page should be switched off, but no modal dialog does it. The HTML Standard gives two cases: content under a loading message, and a menu panel that has slid off the screen. MDN adds: make it plain to see what's inert.
Focus traps and shadow roots
Before <dialog> worked everywhere, people wrote focus traps: code that keeps Tab inside a box. Most look like this:
const stops = dialog.querySelectorAll("button, [href], input, select, textarea, [tabindex]");
const first = stops[0];
const last = stops[stops.length - 1];
dialog.addEventListener("keydown", (event) => {
if (event.key !== "Tab") return;
if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
});- Lines 1 to 3 look for every element Tab can reach, and keep the first and the last.
- Lines 6 to 9 send Tab from the last one back to the first.
Nolan Lawson explains why this breaks in shadow DOM. querySelectorAll() doesn't look inside shadow roots, as lesson 9.4 showed. And document.activeElement gives the host, not the button inside. See it with the kit's quantity in a dialog:
<button commandfor="box" command="show-modal">Choose cups</button><dialog id="box" aria-label="How many cups?"> <tea-quantity></tea-quantity> <button commandfor="box" command="close">Done</button></dialog><script type="module" src="tea-kit/index.js"></script><script> const stops = document.getElementById("box").querySelectorAll("button, [href], input, select, textarea, [tabindex]"); console.log("A focus trap would find:", stops.length); document.addEventListener("keyup", () => { let element = document.activeElement; while (element.shadowRoot?.activeElement) element = element.shadowRoot.activeElement; console.log("Focus:", element.ariaLabel ?? element.textContent); });</script>- Line 3 puts a kit
tea-quantityin the dialog. Its - and + buttons are in its shadow root. - Line 8 runs the trap's search. Line 9 prints how many it found.
- Lines 10 to 14 print the focused element after each key. Line 12 walks into shadow roots to find it.
It prints A focus trap would find: 1: only Done. Click in the result and press Tab: Focus: Choose cups. Press Enter: Focus: One cup less. Tab: Focus: One cup more. Tab: Focus: Done. The real dialog reached all three. A trap built on that search would have kept Tab on Done.
Why it matters: showModal() and inert follow the flat tree, so they work with any component. A hand-made trap doesn't, unless you walk every shadow root yourself. If a component sends events out of a dialog, remember lesson 9.2: only composed events leave its shadow root.
Adding a cart with a checkout dialog to the tea kit
The kit's new version is kitAfter145. One file is new, and every older file stays as it was:
tea-kit/tea-cart.jsistea-cart: the teas added, a Checkout button, and a checkout dialog in its shadow root. A page can send it--clearand--checkout.
Here is the cart with two tea cards:
<tea-card name="Sencha" price="4.50"></tea-card><tea-card name="Mint" price="3.00"></tea-card><tea-cart id="cart"></tea-cart><button commandfor="cart" command="--checkout">Review order</button><button commandfor="cart" command="--clear">Empty cart</button><script type="module" src="tea-kit/index.js"></script><script> const cart = document.getElementById("cart"); document.addEventListener("tea-add", (event) => cart.add(event.tea, event.quantity)); document.addEventListener("tea-order", (event) => { console.log("Ordered:", event.items.map((item) => `${item.tea} × ${item.quantity}`).join(", ")); });</script>- Lines 1 and 2 are two kit tea cards. Line 3 is the cart.
- Lines 4 and 5 are page buttons that send the cart
--checkoutand--clear. - Line 9 adds each card's
tea-addevent to the cart. Lines 10 to 12 print each order.
Click Sencha's Add. Then click Mint's + and its Add. The cart lists Sencha × 1 and Mint × 2. Click the cart's Checkout: focus starts on Keep shopping. Press Esc, and focus goes back to Checkout. Now click Review order on the page. Press Esc again: focus goes back to Review order. Open it once more and click Place order: Ordered: Sencha × 1, Mint × 2.
Here is the cart's shadow root:
<h2 part="heading">Your cart</h2>
<p id="status" part="status" tabindex="-1">Your cart is empty.</p>
<ul part="list"></ul>
<button id="open" part="checkout" commandfor="checkout" command="show-modal" disabled>Checkout</button>
<dialog id="checkout" part="dialog" aria-labelledby="title">
<h2 id="title">Place your order?</h2>
<p id="summary"></p>
<button commandfor="checkout" command="close" value="keep" autofocus>Keep shopping</button>
<button commandfor="checkout" command="close" value="order">Place order</button>
</dialog>`;- Line 4 is Checkout. It sends
show-modalto the dialog in the same root, so the id works. It's disabled while the cart is empty. - Line 5 is the dialog, named by its heading on line 6.
- Line 8 is Keep shopping, with
autofocus: the safe start before a purchase. Lines 8 and 9 close withkeepororder.
this.addEventListener("command", (event) => {
if (event.command === "--clear") this.clear();
if (event.command === "--checkout") this.checkout();
});Line 1 listens on the host. Lines 2 and 3 run clear() or checkout(). Those are public methods too, so script can call them.
const dialog = this.shadowRoot.getElementById("checkout");
dialog.addEventListener("beforetoggle", (event) => {
if (event.newState === "open") dialog.returnValue = "";
});
dialog.addEventListener("close", () => {
if (dialog.returnValue !== "order") return;
const items = this.items;
this.#items = [];
this.#draw("Thanks! Your order is on its way.");
this.shadowRoot.getElementById("status").focus();
this.dispatchEvent(new TeaOrderEvent(items));
});- Lines 2 to 4 empty
returnValueeach time the dialog opens. A close with no value can't replay an old order. - Line 6 lets only
ordergo on. Lines 8 and 9 empty the cart and show a thank-you message. - Line 10 moves focus to that message. If Checkout opened the dialog, it's disabled now, so focus can't go back to it. The APG says to move focus somewhere that makes sense then.
- Line 11 fires
tea-order, which bubbles and is composed.
Read each row of the table across. It compares the boxes this lesson used:
| What you want to know | A modal dialog | A non-modal dialog | An auto popover | A manual popover |
|---|---|---|---|---|
| Can people use the rest of the page? | No. Everything else is inert. | Yes. | Yes. | Yes. |
| Does Esc close it? | Yes, unless closedby is none. | No, unless its closedby says so. | Yes. | No. |
| Does a click outside close it? | Only with closedby set to any. | Only with closedby set to any. | Yes. | No. |
| Where does focus go when it opens? | Inside, to the autofocus element or the first one that takes focus. | Inside, the same way. | It stays on the button, unless something inside has autofocus. | It stays on the button, unless something inside has autofocus. |
| Where does focus go when it closes? | Back to the element that had it before. | Back, if focus was inside it. | Back, if focus was inside it. | Nowhere: it's lost, and you move it yourself. |
- Place your order? with Keep shopping and Place order.
- A list of cup sizes that opens under a Sizes button.
- A tip that shows while you hover over or focus a tea's name.
- A sign-in form that must be filled in before the shopper can go on.
- A note that the brewing timer is running, while you keep shopping.
Sort each box by whether the rest of the page should wait.
Then listen to it, with the VoiceOver and NVDA steps from lesson 14.3. Open the dialog. Listen for its name, Place your order?, then Keep shopping. Press Esc, and listen for Checkout again. The JSDoc and custom-elements.json document the tag, its methods, its event, its commands, and its parts.
Common mix-ups
- "A dialog in a shadow root is stuck inside the component's box." No.
showModal()draws it in the top layer, above every box. - "A modal needs a focus-trap library." No.
showModal()makes everything else inert, through every shadow root. - "commandfor can name an id inside a component." No. Ids are looked up in the button's own tree. Send the host a custom command instead.
- "Any command value reaches my element." No. A custom command must start with
--. - "The command event bubbles to the page." No. Only the target hears it.
- "Closing a dialog clears returnValue." No. A close with no value keeps the old one.
- "Opening a hint popover closes my menu." No. A hint never closes an auto popover.
- "inert shows that something is switched off." No. It changes nothing you can see. Show it yourself.
Practice exercises
For each one, ask what the browser does for you, and what your code still has to do.
Click in the result, press Tab, then Enter. Which button has focus when the dialog opens?
<button commandfor="confirm" command="show-modal">Checkout</button><dialog id="confirm" aria-labelledby="ask"> <p id="ask">Place your order?</p> <button commandfor="confirm" command="close" value="order">Place order</button> <button commandfor="confirm" command="close" value="keep">Keep shopping</button></dialog><script> document.addEventListener("focusin", (event) => console.log("Focus:", event.target.textContent));</script>Place order. It's the first button in the dialog. The page prints Focus: Checkout, then Focus: Place order. Add autofocus to Keep shopping for a safer start.
Click Sizes, then Menu, then click outside both. Which popover is still open?
<button popovertarget="sizes">Sizes</button><button popovertarget="menu">Menu</button><div id="sizes" popover="manual">Small or large</div><div id="menu" popover>Sencha, Mint, Oolong</div><script> for (const popover of document.querySelectorAll("[popover]")) { popover.addEventListener("toggle", (event) => console.log(popover.id, event.newState)); }</script>Sizes. The page prints sizes open, menu open, then menu closed. The click outside light-dismissed the auto menu. The manual Sizes popover stays.
The cart holds 2 cups of Sencha. Fix the Empty cart button, then click it. What does the page print?
<tea-cart id="cart"></tea-cart><button commandfor="cart" command="clear">Empty cart</button><script type="module"> import "./tea-kit/index.js"; const cart = document.getElementById("cart"); cart.add("Sencha", 2); cart.addEventListener("command", () => console.log("Teas in the cart:", cart.items.length));</script><tea-cart id="cart"></tea-cart><button commandfor="cart" command="--clear">Empty cart</button><script type="module"> import "./tea-kit/index.js"; const cart = document.getElementById("cart"); cart.add("Sencha", 2); cart.addEventListener("command", () => console.log("Teas in the cart:", cart.items.length));</script>Teas in the cart: 0. Only line 2 changes, to command="--clear". Without the dashes, the browser fired no command event, so the cart never heard it.
Click Checkout, then Keep shopping. Nothing happens. Fix it, and try again. What does the page print?
<button commandfor="confirm" command="show-modal">Checkout</button><dialog id="confirm" aria-label="Notes for the shop"> <form> <label>Notes <input name="notes"></label> <button commandfor="confirm" command="close" value="keep">Keep shopping</button> </form></dialog><script> const dialog = document.getElementById("confirm"); dialog.addEventListener("close", () => console.log("Closed:", dialog.returnValue));</script><button commandfor="confirm" command="show-modal">Checkout</button><dialog id="confirm" aria-label="Notes for the shop"> <form> <label>Notes <input name="notes"></label> <button type="button" commandfor="confirm" command="close" value="keep">Keep shopping</button> </form></dialog><script> const dialog = document.getElementById("confirm"); dialog.addEventListener("close", () => console.log("Closed:", dialog.returnValue));</script>Closed: keep. Only line 5 changes. Before the fix, Chrome's DevTools console said the button needs type=button, and nothing happened.
Make Remove a cup take one cup away, never going below 0. Click Add a cup twice, then Remove a cup. What does the last line say?
<button commandfor="cups" command="--add">Add a cup</button><button commandfor="cups" command="--remove">Remove a cup</button><button commandfor="cups" command="--clear">Clear</button><tea-counter id="cups"></tea-counter><script src="tea-counter.js"></script><button commandfor="cups" command="--add">Add a cup</button><button commandfor="cups" command="--remove">Remove a cup</button><button commandfor="cups" command="--clear">Clear</button><tea-counter id="cups"></tea-counter><script src="tea-counter.js"></script>--remove from button. Cups: 1. The page stays the same. In the tea-counter.js tab, line 10 is new. Math.max() keeps the count from going below 0.
Click Checkout, then Place order. Then click Checkout and Not now. Order sent prints twice. Fix it. How many times does it print now?
<tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> document.querySelector("tea-checkout").addEventListener("order", () => console.log("Order sent"));</script><tea-checkout></tea-checkout><script src="tea-checkout.js"></script><script> document.querySelector("tea-checkout").addEventListener("order", () => console.log("Order sent"));</script>1. The page stays the same. In the tea-checkout.js tab, lines 14 to 16 replace the comment. Each time the dialog opens, returnValue starts empty, so Not now can't send the old order again.
Check your understanding
For each question, ask where the element lives, and what the browser does for you.
Question 1 of 8tea-checkout's dialog is in its shadow root, and the tag sits in an aside with
overflow: hidden. Where doesshowModal()draw the dialog?Choose an answer to see the explanation.
Question 2 of 8A dialog opened with
showModal()has noclosedby. What closes it?Choose an answer to see the explanation.
Question 3 of 8Click Checkout and Place order, then Checkout and Not now. What does the page print?
Read the code, then predict<button id="open">Checkout</button> <dialog id="confirm" aria-label="Place your order?"> <button id="order">Place order</button> <button id="later">Not now</button> </dialog> <script> const dialog = document.getElementById("confirm"); document.getElementById("open").addEventListener("click", () => dialog.showModal()); document.getElementById("order").addEventListener("click", () => dialog.close("order")); document.getElementById("later").addEventListener("click", () => dialog.close()); dialog.addEventListener("close", () => console.log("returnValue:", dialog.returnValue)); </script>Choose an answer to see the explanation.
Question 4 of 8A page button opens a modal dialog that lives in a component's shadow root. The dialog closes. Where does focus go?
Choose an answer to see the explanation.
Question 5 of 8An auto menu is open. A
popover="hint"tip opens, and it isn't inside the menu. What happens to the menu?Choose an answer to see the explanation.
Question 6 of 8What does a click on Add a cup print here, with the lesson's tea-counter?
Read the code, then predict<button commandfor="cups" command="add">Add a cup</button> <tea-counter id="cups"></tea-counter> <script src="tea-counter.js"></script>Choose an answer to see the explanation.
Question 7 of 8A page button has
commandfor="checkout", the id of the dialog inside tea-cart's shadow root. What does a click do?Choose an answer to see the explanation.
Question 8 of 8Why does a focus trap built on
querySelectorAll()miss tea-quantity's buttons, whenshowModal()doesn't?Choose an answer to see the explanation.
Key takeaways
- A
<dialog>in a shadow root works.showModal()draws it in the top layer, with a::backdropthe component styles. - A modal dialog makes everything else inert, through every shadow root. No focus trap is needed.
closedbypicks the ways out.requestClose()asks first. ResetreturnValuewhen it opens.- Focus moves in, to
autofocusor the first element that takes it, and goes back to the opener on close. - Popovers don't block the page:
autoandhintclose on a click outside, andmanualstays. commandandcommandforwork inside one tree. Custom--commandslet a page drive your element through its host.- The
commandevent doesn't bubble, and itssourceis retargeted like any event target.
Remember the one-liner.
Keep the dialog in your shadow root, open it with showModal(), and let the page send your host --commands.
Sources
The facts on this page come from these standards, docs, and posts:
- <dialog>: the dialog element, MDN.
- HTML Standard: the dialog element, WHATWG.
- HTML Standard: modal dialogs and inert subtrees, WHATWG.
- Dialog (Modal) pattern, W3C WAI-ARIA Authoring Practices.
- Dialogs and shadow DOM: can we make it accessible?, Nolan Lawson.
- popover, MDN.
- HTML Standard: the popover attribute, WHATWG.
- Modern CSS Feature Support For Shadow DOM: Popover API, Adobe Spectrum Web Engineering.
- Interest Invokers (the interestfor attribute), Chrome Platform Status.
- <button>: command and commandfor, MDN.
- Introducing command and commandfor, Keith Cirkel, Chrome for Developers.
- Declarative dialog and popover control, Chrome for Developers, Modern Web Guidance.
- HTML Standard: the custom command keyword, WHATWG.
- CommandEvent: using custom values for commands, MDN.
- HTML Standard: the CommandEvent interface, WHATWG.
- Targeting by Reference in the Shadow DOM, Eric Meyer.
- inert: accessibility concerns, MDN.
- HTML Standard: the inert attribute, WHATWG.
- browser-compat-data, MDN.
Coming next: Color, contrast, and forced colors, in Accessible components. It makes components readable for low vision, color blindness, and Windows high contrast.