By · Updated

Modal Builder

Native HTML Dialog With Dimmed Backdrop, Built-In Focus Handling, Fade, Scale or Slide

No ratings yet

OneTask is free, with no sign-up, and built by one person.
If this tool saved you time, a coffee helps keep new ones coming.

How the Modal Builder works

A modal builder makes a window that opens over the page and asks the visitor to respond before carrying on, such as confirming a delete. This one uses the native HTML <dialog> element. Edit the heading, text and buttons, pick an animation and copy the code.

Calling showModal() on a <dialog> does most of the hard accessibility work for you. The browser moves focus into the dialog, keeps Tab inside it, makes the rest of the page inert so screen readers ignore it, closes it on Escape and returns focus to the button that opened it. Older hand-built modals needed dozens of lines of script to do the same.

How the modal builder closes the dialog

The buttons sit in a form with method="dialog", so pressing either one closes the modal without any script and sets the dialog's returnValue to the button's value, "cancel" or "confirm". A few lines of script also close it when the visitor clicks the dimmed backdrop, and log the result so you can see where to hook in your own action.

Animation

The dialog fades in with @starting-style, and the overlay and display transitions let it fade out too before it leaves the top layer. Browsers without these features open and close the modal instantly, and visitors with reduced motion turned on always get the instant version.

FAQ

Why use the dialog element instead of a div?

A div with role="dialog" needs script to trap focus, hide the page from screen readers, handle Escape and restore focus afterwards, and each of those is easy to get wrong. The dialog element does all of this natively in every current browser.

How do I run code when the visitor confirms?

Listen for the dialog's close event and check dialog.returnValue. It is "confirm" when the confirm button was pressed and "cancel" for the cancel button, Escape or a backdrop click, so only run the delete or save when it equals "confirm".

Which button gets focus when the modal opens?

The first focusable element in the dialog, which is the cancel button here. For destructive actions that is the safer default, because pressing Enter by accident keeps the project. Add autofocus to another button if you want focus to start there instead.

Should I use a modal or a popover?

Use a modal when the visitor must decide before carrying on, because it blocks the rest of the page. For optional help text or a small menu use a popover, which leaves the page usable and closes when the visitor clicks elsewhere.

See also: all UI Components tools, Layout & Spacing, Shadows & Motion, Shapes & SVG, Forms & Inputs, Colour.

Related tools