Challenge 1: Add Escape-to-Close to the Modal — Possible Solution ==================================================================== function openModal(modal, triggerButton) { const previouslyFocused = triggerButton; // Ch.4 Step 3 — remember who to restore focus to const focusables = modal.querySelectorAll("button, a, input, [tabindex]"); focusables[0].focus(); // Ch.4 Step 1 — move focus in function closeModal() { modal.setAttribute("hidden", "true"); modal.removeEventListener("keydown", handleKeydown); previouslyFocused.focus(); // Ch.4 Step 3 — restore focus } function handleKeydown(e) { if (e.key === "Escape") { closeModal(); return; } // ...existing Chapter 4 Tab-trapping logic goes here too... } modal.addEventListener("keydown", handleKeydown); } WHY THIS WORKS -------------- - previouslyFocused captures a reference to triggerButton — the element that had focus immediately before the modal opened — at the very START of openModal(), before focus moves anywhere else. This is the specific detail Chapter 4's own Challenge 3 identified as missing when a modal fails to restore focus correctly: capturing the trigger reference has to happen before Step 1 moves focus away from it. - handleKeydown checks specifically for e.key === "Escape" FIRST, before any Tab-trapping logic — if Escape is pressed, closeModal() runs immediately and the function returns, without falling through to whatever Tab/Shift+Tab cycling logic exists elsewhere in the same handler. - closeModal() does three things in order: hides the modal, removes the keydown listener (so it doesn't keep intercepting keys on a now-hidden element), and calls previouslyFocused.focus() — this last call is Chapter 4's Step 3 in action, returning the user's focus to exactly the button that opened the modal, rather than leaving focus "lost" the way Chapter 4's own Challenge 3 scenario described. - Removing the keydown listener inside closeModal() is a necessary cleanup step often missed — without it, a stale listener could keep firing (or accumulate duplicate listeners) if the same modal element is reused and reopened multiple times across a session.