jQuery's 'keypress' doesn't work for some keys in Chrome. How to work around?

DaveDev picture DaveDev · Oct 10, 2010 · Viewed 46.6k times · Source

I'm trying to implement key-press functionality which will remove a div when the user hits Esc. This works for Firefox & IE with the following code:

$("body").keypress(function(e) {
    alert("any key pressed");
    if (e.keyCode == 27) {
        alert("escape pressed");
    }
});

If I hit any key, the first alert is displayed, and if I hit Escape, the second alert is also displayed.

This doesn't work with Chrome though. The first alert is always displayed if I hit any of the letter keys, but not when I hit Escape, Tab, Space or any of the numbers.

Why would this be? Is there any way to get Chrome to respond to these key presses?

Answer

SLaks picture SLaks · Oct 10, 2010

Try handling keydown instead.