How to detect escape key press?
Asked Answered
M

11

687

How to detect escape key press in IE, Firefox and Chrome? Below code works in IE and alerts 27, but in Firefox it alerts 0

$('body').keypress(function(e){
    alert(e.which);
    if(e.which == 27){
        // Close my modal window
    }
});
Monopoly answered 30/7, 2010 at 7:54 Comment(6)
do some browser detection first?Nez
I find quirksmode.org always reliable to find out what works in which browser: quirksmode.org/js/keys.html . There you can find that only keyup or keydown in combination with keyCode works in all browsers.Funds
I think the title of this question should be "How to detect escape key press with jquery?" Or the answers should be in native javascript...Whiteley
$(document).on("keyup", function (e) {var code = e.keyCode || e.which; alert('key pressed: ' + code);}); Greetings from the 2014Luteolin
Possible duplicate of Which keycode for escape key with jQueryUnilocular
Deprecated/Unsafe -> should use e.key == "Escape"Prognosticate
W
1233

Note: keyCode is becoming deprecated, use key instead.

function keyPress (e) {
    if(e.key === "Escape") {
        // write your logic here.
    }
}

Code Snippet:

var msg = document.getElementById('state-msg');

document.body.addEventListener('keydown', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>

keyCode and keypress are deprecated.

It seems keydown and keyup work.


$(document).keyup(function(e) {
     if (e.key === "Escape") { // escape key maps to keycode `27`
        // <DO YOUR WORK HERE>
    }
});

Which keycode for escape key with jQuery

Wanton answered 30/7, 2010 at 7:59 Comment(13)
to unbind: $(document).unbind("keyup", keyUpFunc);Steelman
To unbind you can also use a namespace on the event, $(document).on('keyup.unique_name', ...) and $(document).unbind('keyup.unique_name')Fungiform
It is recommended to use e.which (instead of e.keycode) to check which key was pressed. jQuery normalizes keycode and charcode (used in older browsers)Congregation
@Congregation : on the same subject, see the comment left by Jordan Brough https://mcmap.net/q/64323/-which-keycode-for-escape-key-with-jqueryLiss
You should always use ===.Tamaratamarack
@pmandell: Other than code style reasons such as consistency, there is no benefit at all to using === over == here.Unseal
@LachlanMcD - be aware (5 years later!) that .unbind is now deprecated as of jQuery 3.0... you should use .offWaldenburg
e.keyCode is deprecated.Goldshell
It seems Chrome does not allow intercepting the Escape key. "keydown" used to work (#3901563), but it seems Google has disabled that as well.Ronna
@Ronna jsfiddle.net/t0bmuaxw I tested in latest chrome available as of today (69.0.3497.100 (Official Build) (64-bit) 21st Sep, 18 keydown is workingWanton
The long list of key values: developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/…Luxuriate
keypress does not work for Escape. Use keydown (or keyup) instead.Einkorn
keypress event is deprecated.Goshawk
U
288

The keydown event will work fine for Escape and has the benefit of allowing you to use keyCode in all browsers. Also, you need to attach the listener to document rather than the body.

Update May 2016

keyCode is now in the process of being deprecated and most modern browsers offer the key property now, although you'll still need a fallback for decent browser support for now (at time of writing the current releases of Chrome and Safari don't support it).

Update September 2018 evt.key is now supported by all modern browsers.

document.onkeydown = function(evt) {
    evt = evt || window.event;
    var isEscape = false;
    if ("key" in evt) {
        isEscape = (evt.key === "Escape" || evt.key === "Esc");
    } else {
        isEscape = (evt.keyCode === 27);
    }
    if (isEscape) {
        alert("Escape");
    }
};
Click me then press the Escape key
Unseal answered 30/7, 2010 at 8:18 Comment(6)
Note, you can also add the listener to an <input> element and it will therefore only be triggered when this element has focus.Jenine
You can also check if (evt.key === 'Escape') { instead of using the deprecated keyCodeFoti
@Keysox: For most modern browsers, yes, although you still need fallbacks for now. I'll edit my answer.Unseal
FYI, MDN's reference to keyCode (includes the deprecation node)Brython
If you want to know if you can safely use .key, see caniuse.com/#feat=keyboardevent-keyChancroid
It seems there's no way in Chrome to get the keydown event from any element, though, when Escape has a form field lose focus (blur). You can try by running the above code snippet, then giving focus to the "Your Answer" text field and hitting "Escape". If anyone has a reliable workaround for this, I would be grateful.Barrelchested
O
46

Using JavaScript you can do check working jsfiddle

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert('Esc key pressed.');
    }
};

Using jQuery you can do check working jsfiddle

jQuery(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       alert('Esc key pressed.');
    }
});
Outgo answered 11/7, 2014 at 6:6 Comment(1)
Intellij says your vanilla js code snippet is deprecated. When should I stop using it ?Tracheo
F
29

Pure JS

you can attach a listener to keyUp event for the document.

Also, if you want to make sure, any other key is not pressed along with Esc key, you can use values of ctrlKey, altKey, and shifkey.

 document.addEventListener('keydown', (event) => {
        
        if (event.key === 'Escape') {
         //if esc key was not pressed in combination with ctrl or alt or shift
            const isNotCombinedKey = !(event.ctrlKey || event.altKey || event.shiftKey);
            if (isNotCombinedKey) {
                console.log('Escape key was pressed with out any group keys')
              
            }
        }
    });
Fy answered 20/10, 2020 at 14:4 Comment(0)
A
21

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});
Absa answered 30/7, 2010 at 7:57 Comment(4)
i see this not working, jsfiddle.net/GWJVt just for the escape... seems awkward?Dyspnea
$(document.body).keypress() is not firingMonopoly
@Reigel: indeed, seems not to work properly with keypress. Whatsoever, I can't figure the 'awkward' part.Absa
KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed.Nowise
A
15

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});
Ajani answered 10/1, 2021 at 19:26 Comment(3)
Hi thanks for answering this question, per site guidelines please add some explanatory text to explain how/why this works. Thanks!Dichloride
As I research and check here onecompiler.com/html/3xy2mfps5. It's better to use key down as it fires for all kinds of keys pressed and use keyCode or code to do UI change(eg; close modal when the user clicks on the escape key).Umeh
keyCode is deprecatedKinakinabalu
N
12

Below is the code that not only disables the ESC key but also checks the condition where it is pressed and depending on the situation, it will do the action or not.

In this example,

e.preventDefault();

will disable the ESC key-press action.

You may do anything like to hide a div with this:

document.getElementById('myDivId').style.display = 'none';

Where the ESC key pressed is also taken into consideration:

(e.target.nodeName=='BODY')

You may remove this if condition part if you like to apply to this to all. Or you may target INPUT here to only apply this action when the cursor is in input box.

window.addEventListener('keydown', function(e){
    if((e.key=='Escape'||e.key=='Esc'||e.keyCode==27) && (e.target.nodeName=='BODY')){
        e.preventDefault();
        return false;
    }
}, true);
Nickelic answered 3/1, 2017 at 4:7 Comment(0)
H
8

Best way is to make function for this

FUNCTION:

$.fn.escape = function (callback) {
    return this.each(function () {
        $(document).on("keydown", this, function (e) {
            var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
            if (keycode === 27) {
                callback.call(this, e);
            };
        });
    });
};

EXAMPLE:

$("#my-div").escape(function () {
    alert('Escape!');
})
Hubblebubble answered 19/11, 2014 at 14:0 Comment(4)
Actually, it seems that keypress doesn't fire on the escape key. At least, not in Chrome on a Mac.Skricki
Thanks for this feedback, I made a update and change rule. keydown fix the problem.Hypoblast
I updated your solution to be able to support an 'only once'-usage. Here is an example: jsfiddle.net/oxok5x2p .Rossi
Cool solution fo rthe only onceHypoblast
R
3

i think the simplest way is vanilla javascript:

document.onkeyup = function(event) {
   if (event.keyCode === 27){
     //do something here
   }
}

Updated: Changed key => keyCode

Rhumb answered 30/11, 2016 at 22:8 Comment(2)
On my chrome (Version 55.0.2883.95 (64-bit)) I get Escape as event.key and not 27Brusquerie
It should be event.keyCode to be 27.Crossly
S
3

On Firefox 78 use this ("keypress" doesn't work for Escape key):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);
Stormystorting answered 17/7, 2020 at 12:10 Comment(0)
P
1

Simple javascript code to detect Escape key is pressed

document.addEventListener("keydown",function(e){
  if(e.key === "Escape") {
    console.log("Escape key pressed")
  }
});
Perla answered 20/9, 2023 at 10:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.