Explain Codes LogoExplain Codes Logo

How to detect escape key press?

javascript
escape-key
event-handling
cross-browser
Anton ShumikhinbyAnton Shumikhin·Aug 8, 2024
TLDR

Detect an Escape key press through a keydown event listener:

document.addEventListener('keydown', event => { if (event.key === "Escape") console.log("Esc pressed - finally free!"); });

This straightforward solution listens for a keydown event, checks for the Escape key, and executes the action.

Extended answer: Covering all the bases

The Fast answer gives you a quick, efficient solution, but let's explore further to create a resilient and adaptive code.

Ensuring cross-browser compatibility

While event.key is standard, to support older browsers, include a check against event.keyCode:

document.addEventListener('keydown', event => { if (event.key === "Escape" || event.keyCode === 27) { console.log("Esc pressed - there's no escape from the past!"); } });

Remember: event.keyCode is deprecated, but the ghost of past code still haunts some older browsers.

Distinguishing clean Escape key presses

Detect Escape key presses without any collateral modifier keys:

document.addEventListener('keydown', event => { if ((event.key === "Escape" || event.keyCode === 27) && !event.shiftKey && !event.ctrlKey && !event.altKey) { console.log("Esc was pressed solo - it's a purist!"); } });

Global vs. specific context detection

Usually, Escape key presses are caught globally (document). In specific contexts, like inside a modal, catch them locally:

var modal = document.getElementById('my-modal'); modal.addEventListener('keydown', function(event) { if (event.key === "Escape") { // Freedom for the modal! } });

Pro tips and precautions for the wary coder

A few more tips and insights to Escape from coding pitfalls.

Always opt for keydown

keypress may ghost you for some keys in certain browsers, especially modifier keys. Stick with keydown.

The jQuery advantage

If you’re into jQuery, detecting key presses is as smooth as a jazz sax solo:

$(document).on('keydown', function(event) { if (event.key === "Escape") { console.log("Escape pressed - jQuery style!"); } });

Test your code across browsers

Ensure your Escape act works in all the browser stages you aim to perform. With online tools and resources, testing is a piece of cake!

Make it user-friendly

If Escape is your way of exiting dialogs or modals, ensure that the UI reflects this action clearly. Your users will thank you!

The drill:

Catch the Escape key press = Club patron sneaking out (🕵️). Listen carefully (👂), check diligently (🔍), then let them leave if it's the right one!

Decoding keypress detection

Let's take apart the mechanics behind the Escape key detection for a lucid comprehension.

Event basics

Each key press sounds an event alarm. The event object carries all the key confidential you need for your mission.

Understanding the event object

Your loyal sidekick event object helps decipher the user's keyboard moves.

Keyboard events in interface interaction

In the UI universe, the Escape key often plays the great abort mission role: closing dialogs, dismissing menus, canceling actions.