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: the dialog element gives you a modal without a library

Javascript
~/tips/tip-html-dialog-showmodal-no-library

Delete this item?

Opens a real modal dialog with a backdrop, focus handling and Escape to close, using one HTML element.

A pop-up used to mean a library and some CSS tricks for the dark overlay. The browser can do it with an element that has been around for a while.


  

Delete this item?

showModal() shows the dialog as a modal in the top layer, so it sits above everything else with a ::backdrop behind it that you can style. Pressing Escape closes it by default.

A form with method="dialog" closes the dialog when submitted, and the value of the button you pressed ends up in dialog.returnValue. A close event fires afterwards, so you can react to the answer.

d.addEventListener('close', () => console.log(d.returnValue));

A call to close() closes it from script, and it cannot be cancelled. If you want a cancellable close, MDN lists requestClose().

The caveat is the other opening method: show() opens it without the modal behaviour, and calling showModal() on a dialog that is already open that way throws an InvalidStateError. Keep to one method per dialog, and give the dialog a clear heading or label so people using a screen reader know what it asks. Focus handling for a modal dialog is done by the browser, which is the biggest reason I would pick this over a hand-made overlay.

Further reading: MDN: dialog element, MDN: HTMLDialogElement.showModal()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link