5

Possible Duplicate:
Which keycode for escape key with jQuery

This little piece of code works like a charm for Firefox and Opera. Internet Explorer doesn't like it.

window.document.onkeydown = function (e) {   
    if (!e) {
        e = event;    
    }
    if (e.keyCode == 27) {
        myfunction();
    }
}

Isn't it possible to detect keydown for ESC in IE? Thanks

Community
  • 1
  • 1
Uli
  • 2,625
  • 10
  • 46
  • 71
  • Not a duplicate of that question. – NetMage Jul 09 '14 at 21:42
  • When I found this question, the answer I was looking for was that when using the modern `event.key` to detect an Escape key press, Internet Explorer uses the code "Esc" despite the standard being "Escape". – Robin Stewart Apr 09 '20 at 04:15

2 Answers2

5

Which version of IE do you have? This code works for me with IE (9.01):

<!doctype html>
<html>
  <head>
    <title></title>
    <script type="text/javascript">
      window.document.onkeydown = function (e)
      {
        if (!e) e = event;
        if (e.keyCode == 27)
          alert("Hello!");
      }
    </script>
  </head>
  <body>
  </body>
</html>

Check also your Doctype, your IE could use the Quirks mode, maybe.

ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • This is very elegant. I just added a conditional `if` that checks a boolean variable to prevent unnecessary execution of code every time the escape key is pressed. i.e. `if (popped_up == true) ...` – Slink Jun 06 '14 at 18:24
1

Some browsers use e.keyCode, others e.charCode. Also, this varies for the type of event, some browsers (like FF) will use one for one type of key, and the other for another type (such as letters vs. arrow keys)

However, testing this in jsfiddle, it looks like e.keyCode is the right check for IE9. Which version of IE are you testing with?

Matt
  • 41,216
  • 30
  • 109
  • 147