CSS Modal Controls with commandfor and command Attributes

Modal controls without onclick handlers

Opening a dialog modally required onclick handlers calling showModal(). Invoker Commands let buttons perform actions on other elements declaratively with commandfor and command attributes.

Old way8 lines
<!-- Inline onclick or JS event listener --><button onclick="  document.querySelector('#dlg') // [!code --]  .showModal()"> // [!code --]  Open Dialog</button><dialog id="dlg">...</dialog>
Modern
6 lines
<button commandfor="dlg" command="show-modal">  Open Dialog</button><dialog id="dlg">...</dialog>
Newly availableSince 202572% global usage

Since 2025 this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Works in all modern browsers. May need a fallback for older browsers.

135+
144+
26.2+
135+
commandfor + command — no onclick handler
Invoker Commands

Opened with commandfor + command="show-modal". No onclick anywhere.

commandfor + command — Chrome 135+
Not supported in this browser
commandfor + command require Chrome 135+

Declarative

Link a button to its target with commandfor (like the for attribute on labels). No querySelector, no addEventListener.

Multiple commands

show-modal, close, show-popover, hide-popover, toggle-popover. One pattern for all interactive elements.

Custom commands too

Prefix with -- for custom commands handled by the command event. Extensible without frameworks.

Lines Saved
8 → 6
Zero JavaScript
Old Approach
onclick handlers
Inline JS or addEventListener
Modern Approach
Invoker Commands
commandfor + command

How it works

To open a <dialog> modally, you needed JavaScript: either an inline onclick that calls showModal(), or an addEventListener in a script. Same for popovers and closing. Every interactive trigger required its own JS wiring.

Invoker Commands add two HTML attributes: commandfor takes the ID of the target element, and command specifies the action. Built-in commands mirror their JS counterparts: show-modal, close, show-popover, hide-popover, toggle-popover. Custom commands prefixed with -- fire a command event on the target for extensibility. Chrome 135, Firefox 144, Safari 26.2, and Edge 135. Baseline Newly available in 2025.

ESC