DEV Community

Cover image for Amazing native Modal with HTML dialog element
Lucas Menezes
Lucas Menezes

Posted on • Updated on

Amazing native Modal with HTML dialog element

The Web as a platform is constantly evolving. And I love it!

Developers no longer need to create complex logics to have a Popup / Modal component in your Web applications.

The HTML dialog element and it's associated events allow you to create fast and accessible native custom dialog boxes.


Top features

All these features below are native of the Dialog element and the browser implementation:

  • Events (open, close, cancel)
  • Autofocus on opened dialog (just press "tab" key to navigate inside)
  • Closes when the user press "esc" key
  • Automatic scroll
  • Keep stacking context (dialog over dialog)
  • Includes a ::backdrop pseudo-element for behind the element

Browser compatibility

Dialog element has 93% of browsers' compatibility, in other words, it is considered full support!

Visit the references Can I Use and MDN Web Docs for more details.

Demo code

I created a simple Demo code that show Dialog element in action and print as the result of user interaction the names of events handled.

Feel free to explore the code πŸ‘‡πŸ»

https://codepen.io/lucasm/pen/YzRBzVQ

Explanation

1) In HTML, you need to create a <dialog> element and attribute an ID to manipulate it

2) Also create an <button> to open the dialog (call event open)

3) Inside the dialog, place any content you want but don't forget to include the action buttons, usually one to confirm the main action and another to close dialog (call event close)

4) In CSS, you can style elements

5) In JavaScript, all logic to handle events

6) A event listener was also placed for when the user press the ESC key! (call event cancel)

That's all Web friends!


I hope you enjoy it!

What are your thoughts on the <dialog> element of HTML? ✨

Top comments (3)

Collapse
 
justanarthur profile image
Arthur Kozubov

just HTML ?

Collapse
 
lucasm profile image
Lucas Menezes

Yes, Dialog is an API from HTML5

But you have to use JavaScript to handle open/close (without aditional code) and CSS to style

Collapse
 
guidari profile image
Guilherme Datilio Ribeiro

Amazing!
Do you know if the tabnavigation will wrap inside the modal at some point, when using the dialogtag?
I heard there is gonna be an update like that