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) });
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.
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.
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.
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.
Try with the keyup event:
$(document).on('keyup', function(e) { if (e.key == "Enter") $('.save').click(); if (e.key == "Escape") $('.cancel').click(); });
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With