Modern HTML: dialog, details and more
Things that used to need JavaScript libraries are now built into HTML: accordions, modals, popovers and autocomplete. Native versions are faster, more accessible and need less code.
Accordions with <details>
Giving <details> elements the same name makes them exclusive: opening one closes the others. They're keyboard-accessible, and their content can be found with Ctrl+F, with zero JavaScript.
Modals with <dialog>
With showModal() you get, for free:
- Focus trapping inside the dialog
- The Escape key to close it
- A styleable
::backdrop - The rest of the page made inert
<form method="dialog"> closes the dialog when a button is clicked, and dialog.returnValue tells you which one.
Popovers: no JavaScript at all
The popover attribute gives you a layer on top of the page that closes when you click outside it or press Escape. It's perfect for menus, tooltips and toasts.
Autocomplete with <datalist>
Reusable markup with <template>
<template> holds HTML that isn't rendered until JavaScript clones it. It's great for lists built from data.
More useful elements and attributes
| Feature | What it does |
|---|---|
<output> |
Displays the result of a calculation |
inert attribute |
Makes a section non-interactive and invisible to assistive tech |
hidden / hidden="until-found" |
Hide content (the second can be revealed by find-in-page) |
enterkeyhint="send" |
Changes the mobile keyboard's Enter key label |
contenteditable |
Makes any element editable |
<search> |
Semantic wrapper for search forms |
Practice
Build a "settings" page using only native HTML features:
- An exclusive
<details>accordion with 3 sections - A "Reset settings" button that opens a confirmation
<dialog> - A help
popovernext to one setting
1.What does dialog.showModal() give you that a styled div doesn't?
2.How do you make several <details> elements behave as an accordion (only one open)?