brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: commandfor and command on a button open a dialog without a click handler

Web-Development
~/tips/tip-button-commandfor-open-dialog

cat ~/tips/tip-button-commandfor-open-dialog.md

Buttons can open modals and toggle popovers declaratively, with no JavaScript.

Opening a modal dialog always needed a line of JavaScript calling showModal(). Invoker commands move that into the HTML, the same way popovertarget did for popovers.

<button commandfor="confirm" command="show-modal">Delete account</button>

<dialog id="confirm">
  <p>Are you sure? This cannot be undone.</p>
  <button commandfor="confirm" command="close">Cancel</button>
  <form method="post" action="/account/delete">
    <button>Delete</button>
  </form>
</dialog>

commandfor takes the id of the element to control and command says what to do. For dialogs the built-in commands are show-modal, close and request-close; for popovers show-popover, hide-popover and toggle-popover.

You can define your own commands too. A value that starts with two dashes, like --rotate, fires a command event on the target, which your script can listen for.

It is new: Chrome 135, Firefox 144 and Safari 26.2. In older browsers the button does nothing at all, which for a delete confirmation is a real problem. Until those versions are common, I would add a small script fallback that checks "commandForElement" in HTMLButtonElement.prototype and wires up the click when it is missing.

Further reading: MDN: Invoker Commands API, MDN: The button element

More Web-Development tips ab -n 200 -c 10 https://example.com/ console.assert(items.length > 0, 'cart is empty', items) document.designMode = "on" function save(item) { Save draft All Web-Development tips (67) All topics

Link