In Ask Before Deleting With a Dialog, Remove learned to ask first. The dialog opened with showModal(), the page behind it waited, and returnValue said which button Sam pressed. That’s the right tool when the page needs an answer. Plenty of panels don’t ask anything, though. They hold a setting or a few tips, and Sam should be able to glance at them and carry on.
In this lesson, you’ll move the Show only today toggle into a List options panel that opens with no JavaScript at all, and you’ll fold the shopping tips away behind a heading Sam can open. You’ll also predict what the keyboard, Escape, and a click outside do for each kind of panel. Start with the area above the list, which has grown crowded.
Open a Panel Without JavaScript
The page above the list now holds the form, Add the usual milk, the Shared list section, three message lines, and the Show only today toggle. Sam uses the toggle now and then, not on every visit, so it can move into a panel that opens on demand.
HTML has an attribute for that. Any element with the popover attribute is a popover, and the browser hides it until something opens it. A button with a popovertarget attribute opens and closes the popover whose id it names. In index.html, replace the Show only today line with these lines:
kitchen/index.html
<button id="list-options-button" type="button"
popovertarget="list-options">List options</button>
<div id="list-options" popover>
<button id="today-only" type="button" aria-pressed="false">
Show only today
</button>
</div>
The toggle keeps its id, so its listener and the aria-pressed line in render() still find it. There’s no new JavaScript. Save, and Live Preview reloads the page. Add eggs (3) and fresh basil (2) with Need it today ticked, and basmati rice (1) without it.
The toggle has gone, and a List options button sits above the list. Tab to it and press Enter. The panel appears with a black border, on top of whatever is underneath:
The browser draws a popover in the top layer, above the rest of the page, where it drew the modal dialog. It places it in the middle of the window by default. Moving it next to its button is a job for CSS that this course doesn’t cover.
The focus stays on List options. Press Tab, and the ring moves to Show only today, inside the panel. An open popover’s buttons come right after the button that opened it in the tab order. Press Enter, and the toggle works as before: basmati rice disappears from the list, and the button turns blue.
Watch out: a popover isn’t a menu. Its buttons stay ordinary buttons that you reach with Tab. If you press Down, the focus stays on Show only today, and a screen reader doesn’t announce a menu either.
The dialog kept the focus inside it until Sam answered. Press Tab again, from Show only today, and the ring lands on Remove eggs while the panel stays open. A popover isn’t modal, so the page behind it keeps working, and the focus can leave.