Dialog and Modals
The HTML <dialog>
element was created for modals and dialogue boxes.
It’s a block level HTML element that comes with several Javascript methods to open and close it, a CSS pseudo-element ::backdrop
, some preconfigured styles such as a border and is automatically centred if a modal.
By default it is closed meaning it’s not visible though you can change this by simply adding the open
attribute to it.
<dialog open>
<!-- content -->
</dialog>
However if it’s opened this way it won’t be a modal. For a modal open with the Javascript showModal()
.
const myModal = document.querySelector('#mymodal');
myModal.showModal();
Javascript
The <dialog>
element comes with 3 Javascript methods:
show()
opens the elementshowModal()
opens it as a modalclose()
is used to close it again.
Even without a close button the modal can be closed by pressing the esc
key on your keyboard. It can also be closed without Javascript using an HTML <form>
element (below).
const modal = document.querySelector('#modal');
const openBtn = document.querySelector('.open-btn');
const closeBtn = document.querySelector('.close-btn');
openBtn.addEventListener('click', () => {
modal.showModal();
})
closeBtn.addEventListener('click', () => {
modal.close();
})
NB. The show()
method has no backdrop and won’t centre the <dialog>
element. Because there’s no backdrop the ::backdrop
pseudo-element is not available either.
Forms
If you place a <form>
element inside your modal and then add an attribute of method="dialog"
when you hit submit on your form the modal will close automatically.
So a simple form with a <button>
or <input type="submit">
button could be used to close the modal.
<form method="dialog">
<button>Close</button>
</form>
The CSS
Here’s an example of some CSS you could use.
dialog {
max-width: 70ch;
padding: 2rem 4rem;
background-color: #2E3641;
color: #fff;
}
dialog::backdrop {
background: #8005;
backdrop-filter: blur(5px);
}