Explain Codes LogoExplain Codes Logo

Which keycode for escape key with jQuery

javascript
event-handling
key-events
jquery
Alex KataevbyAlex Kataev·Nov 17, 2024
⚡TLDR

You can identify the escape key in jQuery by simply declaring the keycode 27. Bind it to the keydown event and compare event.which to 27.

$(document).keydown(function (e) { if (e.which == 27) alert("Look out, escape was just pressed!") });

In one beautiful line, you've trapped the escape key in an alert!

Key event basics: KeyDown, KeyUp and company

Using keyup for user intent

We usually prefer the keyup event; why? Let's think about users. Users tend to hold keys down a little longer than expected. With keyup, we get our event when the user lets go:

$(document).keyup(function(e) { if (e.key == "Escape") alert('User let escape go! Freedom?'); });

Why e.key is your new best friend

Your code is not a place for mystery, use e.key for readability. It comes in handy when Aunt Edna uses Internet Explorer:

$(document).keydown(function(e) { if (e.key == "Escape") alert('Escape is no escape!'); });

The enigma of e.which

Remember, e.which is clinging to past glory. If you are coding for tomorrow (and you should), replace that #hasbeen with e.key.

Dealing with the notorious Enter key

To make friends with the Enter key, try this:

$(document).keydown(function(e) { if (e.key == "Enter") alert('We just made an entry!'); });

Key event handler to the rescue

A key event handler can multitask. Manage those keys like a symphony conductor:

$(document).keydown(function(e) { switch (e.key) { case "Escape": alert('Escape! I feel a song coming on...'); break; case "Enter": $(".save").click(); // Entered the twilight zone break; } });

Advanced: Level up your key event handling game

Contextual event handling

Sometimes, attaching the event to the document is a bit…overkill. Close down your modals with Escape? Easy:

$("#myModal").keyup(function(e) { if (e.key == "Escape") $(this).hide(); // Freedom at last! });

Level up your code with named constants

Replace ambiguity with clarity. Named constants turn your code from mysterious novel to an easy-to-follow comic strip:

const KEY_ESCAPE = "Escape"; $(document).keyup(function(e) { if (e.key == KEY_ESCAPE) alert('Escape from escape!'); });

Cross-browser and legacy friendly

For the good ol' browsers, give event.which one last waltz:

$(document).keyup(function(e) { var key = e.key || e.which; if (key == "Escape" || key == 27) alert('Run forest, run! Escape!'); });