Sam’s list removed an item the moment its Remove button was pressed, so one slip lost the basmati rice for good. In this video, you made Remove ask first with a dialog, watched the page wait while the question was open, and acted only on the answer Remove. Here are the key points:
- The browser’s
confirm()box lets you choose only its message, not its buttons or its look, and a box you build yourself on top of the page leaves the focus and the Escape key to you. A<dialog>element gives you your own buttons and handles the focus and Escape for you. - A
<dialog>stays hidden until your code opens it. Itsaria-labelledbynames it after the question’s paragraph, so screen readers announce the question. - Submitting a form with
method="dialog"inside the dialog closes the dialog instead of sending anything. The form’s buttons send the form, as any button in a form does unless its type says otherwise, and each carries avalue, herekeeporremove. showModal()doesn’t wait for the answer. Unlikeconfirm(), it returns at once, so the removing waits for the dialog to close, in a listener of its own. That listener won’t know which Remove was pressed, so the click listener remembers the button inpendingButton, outside both listeners.showModal()opens the dialog as a modal, so the user has to answer before going back to the page. The focus moves into the dialog, onto its first button, Keep it, so Enter right away is the safe answer. A light gray backdrop covers the page. Clicking Remove eggs does nothing, and Tab moves to Remove, then out to the browser’s toolbar, never to the list. The page behind is inert.- When the dialog closes, it fires a
closeevent, and the dialog’sreturnValueholds the value of the button that closed it. Keep it gives"keep". - Escape closes the dialog too, with no button. Firefox and Safari then leave
returnValueas it was, even"remove"from an earlier answer, so Escape would remove the next item too. The click listener therefore sets it to an empty string beforeshowModal(). Escape then leaves that empty string, and nothing is removed. - Watch out:
show(), or anopenattribute you write on the dialog yourself, displays it too, but not as a modal. The page behind stays clickable, and Escape does nothing.showModal()setsopenfor you, so always open the dialog with it. - The browser returns the focus to the button that opened the dialog, before the
closeevent fires. After a removal, your code moves it on to the neighbor’s Remove button, as before.
In kitchen/index.html, the dialog goes right after the list:
kitchen/index.html
<ul id="items"></ul>
<dialog id="confirm-remove" aria-labelledby="confirm-text">
<form method="dialog">
<p id="confirm-text"></p>
<button value="keep">Keep it</button>
<button value="remove">Remove</button>
</form>
</dialog>
In kitchen/main.js, two lookups and a variable for the button that opened the dialog go next to the others: