How to create pop ups or a modal using the new HTML dialog element

Finally we can use a new HTML tag called dialog element to create pop ups and modals in our design. The browser support is around 70% which is not too bad.It will increase quickly as it is a new element in 2018.

The dialog element

Typically we can use dialog element to create modals and popups using Javascript to set the behaviour. Here is a simple dialog tag:

<dialog open>
  <p>A simple dialog box which is open by default!</p>

As the above example shows we have an open attribute in dialog element. The open attribute indicates that the dialog is active and available for user interaction.

Specifications of dialog box

Basically these are some specifications of the dialog box:

  • Easy to show and hide, including an open boolean attribute
  • Having  a ::backdrop pseudo element for modal types.
  • Includes two version of popup and modals
  • In Dom it has methods like** show , showModal , and close and open** attribute.

Standard popup

Surprisingly we could create a simple popup using dialog tag with a short Javascript code:

<dialog id="popup">
  <h1>I am a simple popup</h1>
<button id="showPopup" onClick="showPopup()">show simple popup</button>

  const showPopup = ()  => {
    const popup = document.getElementById('popup');;

Using show method we now have a simple dialog box using pure HTML and Javascript.

popup or modal!

Modal box

However we need to use showModal method to create a modal box with dialog tag. It will also shows up on top of all elements no matter what z-index is. It will have a dialog::backdrop for stying and it could be closed using ESC key.

<dialog id="modal">
  <h1>I am a Modal</h1>
<button id="showModal" onClick="showModal()">show simple popup</button>

  const showModal = ()  => {
    const modal = document.getElementById('modal');

Using dialog attribute in a form

Greatly we are able to use an attribute called method=”dialog”  in our forms that are within a dialog elements. Specifying the attribute provides the contents of the submit button’s value attribute to the dialog element itself.

<dialog id="form">
  <form method="dialog">
    <p>Would you like to continue?</p>
    <button type="submit" value="no">No</button>
    <button type="submit" value="yes">Yes</button>
<button id="showForm" onClick="showForm()">show form</button>

const form = document.getElementById('form');
const showForm = () => form.showModal();
form.addEventListener('close',  (event) => {
    if (dialog.returnValue === 'yes') { /* … */ }

I have created a pen to demonstrate them all. We can manipulate them. Add cancel button to close them as well.

Great. We now know about a great element which can solve our problems to create popups or modals inside HTML code.

Thank you for reading.

© 2019
Azadeh Faramarzi

This site is created and maintined by Azadeh Faramarzi , A passionate developer, sport and code lover who loves to share and write when she has some time.