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)
just HTML ?
Yes, Dialog is an API from HTML5
But you have to use JavaScript to handle open/close (without aditional code) and CSS to style
Amazing!
Do you know if the
tab
navigation will wrap inside the modal at some point, when using thedialog
tag?I heard there is gonna be an update like that