Native Modal Dialog implementation

Excerpt

Almost there: Modal dialogs in the browser.

You may have implemented applications that require focused user input. The "Modal Dialog" approach is often used for the simplicity of implementing it. However the real blocking modal dialogs are window.alert and window.prompt only.

There are many articles on how to implement a almost modal behavior in the browser but making it robust is a long story.

The <dialog> element is promissing as it adds native support to the topic. In 2021 the chrome based browsers do have full standard support already and safari will follow as announced.

How it works

Implementing a modal dialog gets quiet easy by creating a <dialog> element on the body level. It is not visible by default. Now use some scripting to call the showModal() function.

<dialog id="simple">
  <h2>This is a dialog</h2>
  <p>Use the `esc` key to close (or reload the page).</p>
</dialog>

This is a dialog

Use the <esc> key to close (or reload the page).

Some CSS can be used to define the Layout of the dialogs, especially the ::backdrop pseudo elementcan be styled:

dialog::backdrop {
  background-color: rgba(200, 200, 200, 0.7);
}

dialog {
  padding: 0.5em;
  background-color: Canvas;
  border: 0;
  box-shadow: .4em .4em #888888;
}

One benfit is that all the elements outside the dialog element will not get the input focus any more.

More scripting required

The HTML element alone doesn't create a perfect modal dialog solution. Using some JavaScrip tou may resolve:

A more complex example of 2 chained dialogs also uses the <form> element with method="dialog" can be found here too including some scripts that solves some problems from above.

Step 1 of 2

Native modal dialogs are awesome.

Step 2 of 2

This is awesome

See also

Tags

JavaScript