Thursday, April 19, 2012

How to detect escape key press with javascript



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


Source: Tips4all

4 comments:

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

    ReplyDelete
  2. 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");
    }
    };

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

    ReplyDelete
  4. check for keyCode && which & keyup || keydown

    $(document).keydown(function(e){
    var code = e.keyCode ? e.keyCode : e.which;
    alert(code);
    });

    ReplyDelete