views:

225

answers:

4

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
            }
        });
A: 

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode ? e.keyCode : e.which;
   alert(code);
});
jAndy
i see this not working, http://jsfiddle.net/GWJVt/ just for the escape... seems awkward?
Reigel
$(document.body).keypress() is not firing
Mithun P
@Reigel: indeed, seems not to work properly with keypress. Whatsoever, I can't figure the 'awkward' part.
jAndy
+1  A: 
$(document).keyup(function(e) {

  if (e.keyCode == 27) { <DO YOUR WORK HERE> }   // esc
});

http://stackoverflow.com/questions/1160008/which-keycode-for-escape-key-with-jquery

org.life.java
+1  A: 

either use .keydown() or .keyup()...

Reigel
yea, along with document and not with 'body'
Mithun P
@Mithun correct!
Reigel
+1  A: 

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:

document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        alert("Escape");
    }
};
Tim Down