Issue #21: closing dialogs
Issue #21: closing dialogs
I’m really excited about the dialog element because it makes creating (modal) dialogs so much easier. The element doesn’t just come with new methods and events in JavaScript, but also with new attribute values in HTML.
If you want to open a modal, you have to add an event to a button and either call the show()
or the showModal()
method. If you want to close a modal, you can call the close()
method or you can put a button inside a form with the method
attribute set to “dialog” inside the modal.
<dialog>
<form method="dialog">
<button>Close</button>
</form>
<h1>Hey!</h1>
</dialog>
<button class="openButton">Show modal</button>
<script>
const dialog = document.querySelector('dialog');
openButton.addEventListener('click', e => {
dialog.showModal();
})
</script>
Pretty cool that HTML can do that, right?
The dialog method doesn’t just enable closing the modal. Closing also fires the close event.
const dialog = document.querySelector('dialog');
dialog.addEventListener('close', e => {
console.log(e.type)
})
You can try it yourself on CodePen.
Don't miss what's next. Subscribe to HTMHell Newsletter: