Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which keycode for escape key with jQuery

I have two functions. When enter is pressed the functions runs correctly but when escape is pressed it doesn't. What's the correct number for the escape key?

$(document).keypress(function(e) {      if (e.which == 13) $('.save').click();   // enter (works as expected)     if (e.which == 27) $('.cancel').click(); // esc   (does not work) }); 
like image 746
Shishant Avatar asked Jul 21 '09 15:07

Shishant


People also ask

Which F key is escape?

The Escape key is located in the upper-left corner of a computer keyboard. It typically resides to the left of the Function keys (F1, F2, F3, etc.) and above the tilde (~) key.

How do I know if my Esc is pressed?

To detect escape key press, keyup or keydown event handler will be used in jquery. It will trigger over the document when the escape key will be pressed from the keyboard. keyup event: This event is fired when key is released from the keyboard.

Is there an alternative to the Escape key?

If you have an American English keyboard, pressing Ctrl-[ (control plus left square bracket) is equivalent to pressing Esc. This provides an easy way to exit from insert mode.

Is Escape key a function key?

What is the Esc key? The Esc key, simply “Esc” on a keyboard, is a control key. Like the function keys or the Alt and Ctrl keys, it doesn't generate a character when writing a text.


2 Answers

Try with the keyup event:

$(document).on('keyup', function(e) {   if (e.key == "Enter") $('.save').click();   if (e.key == "Escape") $('.cancel').click(); }); 
like image 194
Christian C. Salvadó Avatar answered Sep 21 '22 17:09

Christian C. Salvadó


Rather than hardcode the keycode values in your function, consider using named constants to better convey your meaning:

var KEYCODE_ENTER = 13; var KEYCODE_ESC = 27;  $(document).keyup(function(e) {   if (e.keyCode == KEYCODE_ENTER) $('.save').click();   if (e.keyCode == KEYCODE_ESC) $('.cancel').click(); }); 

Some browsers (like FireFox, unsure of others) define a global KeyEvent object that exposes these types of constants for you. This SO question shows a nice way of defining that object in other browsers as well.

like image 43
Seth Petry-Johnson Avatar answered Sep 21 '22 17:09

Seth Petry-Johnson