674

Possible Duplicate:
Which keycode for escape key with jQuery

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
    }
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mithun Sreedharan
  • 49,883
  • 70
  • 181
  • 236
  • 1
    do some browser detection first? – ina Jul 30 '10 at 08:01
  • 7
    I find quirksmode.org always reliable to find out what works in which browser: http://www.quirksmode.org/js/keys.html . There you can find that only `keyup` or `keydown` in combination with `keyCode` works in all browsers. – Felix Kling Jul 30 '10 at 08: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 '14 at 14:27
  • 3
    `$(document).on("keyup", function (e) {var code = e.keyCode || e.which; alert('key pressed: ' + code);});` Greetings from the 2014 – Kalle H. Väravas Mar 02 '14 at 18:14
  • Possible duplicate of [Which keycode for escape key with jQuery](https://stackoverflow.com/questions/1160008/which-keycode-for-escape-key-with-jquery) – Cœur Jul 10 '18 at 13:33

10 Answers10

1210

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('keypress', function(e) {
  if (e.key == "Escape") {
    msg.textContent += 'Escape pressed:'
  }
});
Press ESC key <span id="state-msg"></span>

keyCode is becoming deprecated

It seems keydown and keyup work, even though keypress may not


$(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

Aryan Beezadhur
  • 4,503
  • 4
  • 21
  • 42
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 14
    to unbind: $(document).unbind("keyup", keyUpFunc); – Plattsy May 06 '13 at 05:32
  • 63
    To unbind you can also use a namespace on the event, `$(document).on('keyup.unique_name', ...)` and `$(document).unbind('keyup.unique_name')` – Lachlan McDonald May 13 '13 at 03: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 '14 at 11:51
  • 1
    @DMTintner : on the same subject, see the comment left by Jordan Brough http://stackoverflow.com/a/1160109/759452 – Adriano Aug 18 '14 at 13:48
  • 9
    You should always use `===`. – pmandell Feb 03 '16 at 17:02
  • @pmandell: Other than code style reasons such as consistency, there is no benefit at all to using `===` over `==` here. – Tim Down Apr 12 '18 at 14:00
  • 4
    @LachlanMcD - be aware (5 years later!) that [`.unbind`](http://api.jquery.com/unbind/) is now deprecated as of jQuery 3.0... you should use [`.off`](http://api.jquery.com/off/) – freefaller Apr 24 '18 at 14:07
  • e.keyCode is deprecated. – Dieter Donnert Sep 19 '18 at 16:32
  • It seems Chrome does not allow intercepting the Escape key. "keydown" used to work (https://stackoverflow.com/questions/3901063/jquerys-keypress-doesnt-work-for-some-keys-in-chrome-how-to-work-around/5479683), but it seems Google has disabled that as well. – Spero Sep 21 '18 at 16:30
  • 1
    @Spero https://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 working – jmj Sep 21 '18 at 19:38
  • 1
    2019-07-04 : Does not work in lasted Chrome on ChromeBook. I tried the Fiddle. Nothing made it work. – FlorianB Jul 04 '19 at 15:21
  • 1
    The long list of **key values**: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values – Bob Stein Nov 22 '19 at 23:48
  • `keypress` does **not** work for `Escape`. Use `keydown` (or `keyup`) instead. – Lideln Kyoku Aug 18 '22 at 12:39
281

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
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • 3
    Note, you can also add the listener to an `` element and it will therefore only be triggered when this element has focus. – Mike Feb 19 '13 at 01:14
  • 1
    You can also check `if (evt.key === 'Escape') {` instead of using the deprecated `keyCode` – Keysox May 19 '16 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 '16 at 10:51
  • FYI, [MDN's reference to keyCode](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode) (includes the deprecation node) – Steven Jun 01 '16 at 23:37
  • 1
    If you want to know if you can safely use `.key`, see https://caniuse.com/#feat=keyboardevent-key – Jasper de Vries Jan 14 '18 at 18:51
  • 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. – Aurélien Martin Apr 12 '18 at 10:42
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.');
    }
});
Subodh Ghulaxe
  • 18,333
  • 14
  • 83
  • 102
23

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')
              
            }
        }
    });
Irshad
  • 1,016
  • 11
  • 30
21

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});
poxip
  • 909
  • 8
  • 25
jAndy
  • 231,737
  • 57
  • 305
  • 359
15

pure JS (no JQuery)

document.addEventListener('keydown', function(e) {
    if(e.keyCode == 27){
      //add your code here
    }
});
ZeroBased_IX
  • 2,667
  • 2
  • 25
  • 46
Divya Prakash
  • 171
  • 1
  • 4
  • Hi thanks for answering this question, per site guidelines please add some explanatory text to explain how/why this works. Thanks! – Nathaniel Flick Jan 10 '21 at 21:03
  • As I research and check here https://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). – Himanshu Joshi Apr 03 '22 at 15:25
  • 2
    `keyCode` is deprecated – Shaya Ulman May 05 '22 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);
Tarik
  • 4,270
  • 38
  • 35
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!');
})
Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
3

i think the simplest way is vanilla javascript:

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

Updated: Changed key => keyCode

Gopala Raja Naika
  • 2,321
  • 23
  • 18
Duan Walker
  • 305
  • 1
  • 11
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);
Petr L.
  • 414
  • 5
  • 13