683

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
    }
});
6
  • 1
    do some browser detection first?
    – ina
    Jul 30, 2010 at 8:01
  • 7
    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. Jul 30, 2010 at 8:02
  • 2
    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...
    – Wilt
    Jan 30, 2014 at 14:27
  • 3
    $(document).on("keyup", function (e) {var code = e.keyCode || e.which; alert('key pressed: ' + code);}); Greetings from the 2014 Mar 2, 2014 at 18:14
  • Possible duplicate of Which keycode for escape key with jQuery
    – Cœur
    Jul 10, 2018 at 13:33

11 Answers 11

1218

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

13
  • 14
    to unbind: $(document).unbind("keyup", keyUpFunc);
    – Plattsy
    May 6, 2013 at 5:32
  • 63
    To unbind you can also use a namespace on the event, $(document).on('keyup.unique_name', ...) and $(document).unbind('keyup.unique_name') May 13, 2013 at 3:32
  • 9
    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)
    – DMTintner
    Mar 18, 2014 at 11:51
  • 9
    You should always use ===.
    – pmandell
    Feb 3, 2016 at 17:02
  • 4
    @LachlanMcD - be aware (5 years later!) that .unbind is now deprecated as of jQuery 3.0... you should use .off
    – freefaller
    Apr 24, 2018 at 14:07
283

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

6
  • 3
    Note, you can also add the listener to an <input> element and it will therefore only be triggered when this element has focus.
    – Mike
    Feb 19, 2013 at 1:14
  • 1
    You can also check if (evt.key === 'Escape') { instead of using the deprecated keyCode
    – Keysox
    May 19, 2016 at 17:17
  • @Keysox: For most modern browsers, yes, although you still need fallbacks for now. I'll edit my answer.
    – Tim Down
    May 20, 2016 at 10:51
  • FYI, MDN's reference to keyCode (includes the deprecation node)
    – Steven
    Jun 1, 2016 at 23:37
  • 1
    If you want to know if you can safely use .key, see caniuse.com/#feat=keyboardevent-key Jan 14, 2018 at 18:51
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.');
    }
});
1
  • Intellij says your vanilla js code snippet is deprecated. When should I stop using it ? Nov 2, 2020 at 21:42
26

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')
              
            }
        }
    });
21

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});
4
  • 1
    i see this not working, jsfiddle.net/GWJVt just for the escape... seems awkward? Jul 30, 2010 at 8:06
  • $(document.body).keypress() is not firing Jul 30, 2010 at 8:11
  • @Reigel: indeed, seems not to work properly with keypress. Whatsoever, I can't figure the 'awkward' part.
    – jAndy
    Jul 30, 2010 at 8:11
  • 3
    KeyPress is raised for character keys (unlike KeyDown and KeyUp, which are also raised for noncharacter keys) while the key is pressed.
    – Marta
    Sep 16, 2015 at 13:22
15

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});
3
  • Hi thanks for answering this question, per site guidelines please add some explanatory text to explain how/why this works. Thanks! Jan 10, 2021 at 21:03
  • 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). Apr 3, 2022 at 15:25
  • 3
    keyCode is deprecated May 5, 2022 at 13:50
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);
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!');
})
4
  • 6
    Actually, it seems that keypress doesn't fire on the escape key. At least, not in Chrome on a Mac.
    – samson
    Jul 20, 2015 at 18:36
  • 1
    Thanks for this feedback, I made a update and change rule. keydown fix the problem. Jul 21, 2015 at 9:04
  • 1
    I updated your solution to be able to support an 'only once'-usage. Here is an example: jsfiddle.net/oxok5x2p .
    – d.h.
    Aug 8, 2016 at 7:19
  • Cool solution fo rthe only once Oct 27, 2020 at 7:30
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);
3

i think the simplest way is vanilla javascript:

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

Updated: Changed key => keyCode

2
  • 6
    On my chrome (Version 55.0.2883.95 (64-bit)) I get Escape as event.key and not 27
    – MosheZada
    Dec 25, 2016 at 20:20
  • It should be event.keyCode to be 27. Jan 28, 2020 at 8:59
1

Simple javascript code to detect Escape key is pressed

document.addEventListener("keydown",function(e){
  if(e.key === "Escape") {
    console.log("Escape key pressed")
  }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.