Course contentsShow
← Web Development
Lesson 1168 of 2,98221. Accessible ComponentsFree lesson

Escape Key and Click-Outside Handling

Closing dropdowns with Escape key and handling outside clicks while maintaining accessibility.

Escape Key and Click-Outside Handling

What you'll learn: How to close dropdowns gracefully when users press Escape or click outside, while maintaining accessibility standards.

When building accessible dropdowns, you need to provide intuitive ways to dismiss them. Users expect dropdowns to close when they press the Escape key or click anywhere outside the menu—just like closing a file dialog by clicking away or hitting Escape on your keyboard. These interactions must be handled explicitly in your code.

Implementing Escape Key Handling

Building on your earlier Escape Key Handling lesson, attach a keydown listener to the dropdown menu:

menu.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    closeMenu();
    menuButton.focus(); // Return focus to trigger button
  }
});

This ensures keyboard users can dismiss the dropdown and have focus properly restored to the button that opened it—completing the focus management pattern you've already learned.

Handling Click-Outside

To detect clicks outside the dropdown, listen for clicks on the entire document and check if the click target is outside your dropdown container:

document.addEventListener('click', (e) => {
  const isClickInside = dropdown.contains(e.target);
  const isButton = menuButton.contains(e.target);
  
  if (!isClickInside && !isButton && menuOpen) {
    closeMenu();
  }
});

Why exclude the button? The button has its own toggle logic. Including it in click-outside handling would conflict with opening the menu.

Combining Both Patterns

These two patterns work together to create an intuitive dismissal experience—Escape for keyboard users, click-outside for mouse users—both returning focus appropriately and maintaining the expected user flow.

Key Takeaway: Implement both Escape key and click-outside handlers to give users multiple, accessible ways to dismiss dropdowns, always managing focus properly when closing.