Which keycode for escape key with jQuery - javascript

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

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.

(Answer extracted from my previous comment)
You need to use keyup rather than keypress. e.g.:
$(document).keyup(function(e) {
if (e.which == 13) $('.save').click(); // enter
if (e.which == 27) $('.cancel').click(); // esc
});
keypress doesn't seem to be handled consistently between browsers (try out the demo at http://api.jquery.com/keypress in IE vs Chrome vs Firefox. Sometimes keypress doesn't register, and the values for both 'which' and 'keyCode' vary) whereas keyup is consistent.
Since there was some discussion of e.which vs e.keyCode: Note that e.which is the jquery-normalized value and is the one recommended for use:
The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.
(from http://api.jquery.com/event.which/)

To find the keycode for any key, use this simple function:
document.onkeydown = function(evt) {
console.log(evt.keyCode);
}

27 is the code for the escape key. :)

Your best bet is
$(document).keyup(function(e) {
if (e.which === 13) $('.save').click(); // enter
if (e.which === 27) $('.cancel').click(); // esc
/* OPTIONAL: Only if you want other elements to ignore event */
e.preventDefault();
e.stopPropagation();
});
Summary
which is more preferable than keyCode because it is normalized
keyup is more preferable than keydown because keydown may occur multiple times if user keeps it pressed.
Do not use keypress unless you want to capture actual characters.
Interestingly Bootstrap uses keydown and keyCode in its dropdown component (as of 3.0.2)! I think it's probably poor choice there.
Related snippet from JQuery doc
While browsers use differing
properties to store this information, jQuery normalizes the .which
property so you can reliably use it to retrieve the key code. This
code corresponds to a key on the keyboard, including codes for special
keys such as arrows. For catching actual text entry, .keypress() may
be a better choice.
Other item of interest: JavaScript Keypress Library

Try the jEscape plugin (download from google drive)
$(document).escape(function() {
alert('ESC button pressed');
});
or get keycode for cross browser
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 27) alert('ESC');
if (code === 13) alert('ENTER');
maybe you can use switch
var code = (e.keyCode ? e.keyCode : e.which);
switch (code) {
case 27:
alert('ESC');
break;
case 13:
alert('ENTER');
break;
}

Just posting an updated answer than e.keyCode is considered DEPRECATED on MDN.
Rather you should opt for e.key instead which supports clean names for everything. Here is the relevant copy pasta
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
switch (event.key) {
case "ArrowDown":
// Do something for "down arrow" key press.
break;
case "ArrowUp":
// Do something for "up arrow" key press.
break;
case "ArrowLeft":
// Do something for "left arrow" key press.
break;
case "ArrowRight":
// Do something for "right arrow" key press.
break;
case "Enter":
// Do something for "enter" or "return" key press.
break;
case "Escape":
// Do something for "esc" key press.
break;
default:
return; // Quit when this doesn't handle the key event.
}
// Cancel the default action to avoid it being handled twice
event.preventDefault();
}, true);

Your code works just fine. It's most likely the window thats not focused. I use a similar function to close iframe boxes etc.
$(document).ready(function(){
// Set focus
setTimeout('window.focus()',1000);
});
$(document).keypress(function(e) {
// Enable esc
if (e.keyCode == 27) {
parent.document.getElementById('iframediv').style.display='none';
parent.document.getElementById('iframe').src='/views/view.empty.black.html';
}
});

I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...
if (keyCode == 27)
{
history.back();
if (window.event)
{
// IE works fine anyways so this isn't really needed
e.cancelBubble = true;
e.returnValue = false;
}
else if (e.stopPropagation)
{
// In firefox, this is what keeps the escape key from canceling the history.back()
e.stopPropagation();
e.preventDefault();
}
return (false);
}

To explain where other answers haven't; the problem is your use of keypress.
Perhaps the event is just mis-named but keypress is defined to fire when when an actualcharacteris being inserted. I.e. text.
Whereas what you want is keydown/keyup, which fires whenever (before or after, respectively) the user depresses akey. I.e. those things on the keyboard.
The difference appears here because esc is a control character (literally 'non-printing character') and so doesn't write any text, thus not even firing keypress.
enter is weird, because even though you are using it as a control character (i.e. to control the UI), it is still inserting a new-line character, which will fire keypress.
Source: quirksmode

To get the hex code for all the characters: http://asciitable.com/

A robust Javascript library for capturing keyboard input and key combinations entered. It has no dependencies.
http://jaywcjlove.github.io/hotkeys/
hotkeys('enter,esc', function(event,handler){
switch(handler.key){
case "enter":$('.save').click();break;
case "esc":$('.cancel').click();break;
}
});
hotkeys understands the following modifiers: ⇧,shiftoption⌥altctrlcontrolcommand, and ⌘.
The following special keys can be used for shortcuts:backspacetab,clear,enter,return,esc,escape,space,up,down,left,right,home,end,pageup,pagedown,del,delete andf1 throughf19.

I have always used keyup and e.which to catch escape key.

I know this question is asking about jquery, but for those people using jqueryui, there are constants for many of the keycodes:
$.ui.keyCode.ESCAPE
http://api.jqueryui.com/jQuery.ui.keyCode/

$(document).on('keydown', function(event) {
if (event.key == "Escape") {
alert('Esc key pressed.');
}
});

Related

Get the keypress code without to care which symbol is clicked using JQuery

I see here is have few questions when is asking for how can get which key is clicked from keyboard. I tested is ok is working if is in English case.
If I change the language and the symbols on keyboard is changed then is not show anything.
So my question is how can I get the keypress code without to care which language is now used the user when is click the key 'G' or 'Г' or something else.
here is my simple jquery code
$(document).keypress(function(e) {
if (e.charCode == 103) {
alert('g');
} else if (e.charCode == 71) {
alert('G');
}
});
If is with english is working, when I change to Bulgarian then is not working. How can I make to working on every language?
Using the keypress event will give you the character typed, regardless of keyboard layout.
For character input, it is suggested you use keypress(), which will report the actual ASCII code for the character pressed. It automatically takes care of letter case, and ignores non-character presses. In either case, you can use fromCharCode() to convert to a string representation. E.g.
document.onkeypress = function(evt) {
evt = evt || window.event;
var charCode = evt.which || evt.keyCode;
var charTyped = String.fromCharCode(charCode);
alert("Character typed: " + charTyped);
};
I find the solution of my problem. Thanks of this article
$(document).on('keydown', function(e) {
if (e.ctrlKey) {
alert('Echo');
} else {
alert(e.which + ' ' + e.key);
}
});
What I'm changing. I change only the event. I replace 'keypress' with 'keydown' and now is the same code without to care which language is used.

I Need a way to execute a particular function when i press the forward key or the back key in javascript

I need a way to execute a particular function when I press the forward key or the back key in javascript. So that it may work when the forward button is pressed it may execute the function but it should work without taking the input in any type of text box.
I mean it should work on the whole page no matter where I am on the page but if I press the forward button the function should be executed.
I know how to do it by taking an input in a text box by matching the key codes but don't know how to make it work in someway else.
If by forward and back keys you mean the arrow keys, this is how you can do it!
document.onkeydown = function(e) {
e = e || window.event;
switch(e.which || e.keyCode) {
case 37: // left
break;
case 38: // up
break;
case 39: // right
break;
case 40: // down
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action
});
I feel pretty confident with my assumption that you are referring to the arrow keys on the keyboard. And as you say you already have working code for when a textbox is focused, I also assume you are using onkeydown (or one of the similar ones) already. So the solution is to add the event listener to the document instead.
Like this for example:
document.onkeydown = function(e){
// Your existing code goes here.
}
You need to use onkeydown if you want to detect arrow keys.
Here is a working example
Use onkeydown as this should work for all browsers. I don't think onkeypress will work with google chrome for the arrow key events.
38 = Up Arrow
40 = Down Arrow
To find more you can use console.log(event.keyCode); in your onkeydown function to log the key codes to your browsers console.
function MyFunc() {
alert("Key up or down!");
}
document.onkeydown = function() {
if (event.keyCode == 38 || event.keyCode == 40) {
MyFunc();
}
}
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

jQuery not detecting modifiers on keyup

When I run the following code and press the command key on my Mac (using Chrome), metaKey is set for keydown but not for keyup. Am I doing something wrong? I'm just trying to track the meta key being pressed so I can use it inside my JavaScript - if there's a better way please let me know :-)
var metaPressed = false;
$(document).keydown(function(e) {
console.log('keydown ' + e.keyCode);
if (e.metaKey || e.ctrlKey) {
console.log('meta pressed');
metaPressed = true;
}
});
$(document).keyup(function(e) {
console.log('keyup ' + e.keyCode);
if (e.metaKey || e.ctrlKey) {
console.log('meta unpressed');
metaPressed = false;
}
});
Here's the console output for the relevant keys
// Pressing cmd
keydown 91
meta pressed
keyup 91
// Pressing control
keydown 17
meta pressed
keyup 17
// Pressing non-meta like spacebar
keydown 32
keyup 32
I get it now, I was misunderstanding how jQuery handles modifier keys. Thanks to #adeneo for the prompt that got me thinking correctly.
Also, if you press keys while holding a meta character, e.g. press M-x, jQuery doesn't send the keyup for 'x' until it the 'M' is also released. So you don't have to worry about things like "meta down, x down, x up, meta up" happening
You won't be able to retrieve that information from the keyup. I would recommend to use this (e.keyCode === 17 || e.keyCode === 91) as test case (which are CTRL and META respectively)
I'm using React and noticing the same issue. e.metaKey works on keydown but not keyup. e.keyCode is 93 for both, however.

how to capture backspace key code in android browser - javascript?

I have a page made in pure HTML Javascript... I handle the keyup code and I need to get the key code, when key code == 8 (backspace) special task must be run... but if I open the page in android browser, chrome, or whatever... backspace doesn't return any key code...
I've made:
$( '.input-cell' ).bind( 'keyup', function( e ){
var keycode = e.keyCode ? e.keyCode : e.which;
alert( keycode );
if( keycode == 8 ) {
.....
}
});
The alert returns me all the keycodes but the backspace... is there any way to capture the backspace press event?
input change event
$('#myinput').bind('input', function(){
// code
});
backspace
$('#myinput').on('keypress', function() {
//code
}).on('keydown', function(e) {
if (e.keyCode==8) {
//code
}
});
Another solution can be check for the length of the characters before, and after, if it has less than one character than before, then clearly it was a backspace that fired, in my case I was using only one input with one character and needed to go back to the previous input after hitting a backspace, for my case I only got also 0 and 229 within the android keyboard, so I did this:
$('input').on('keydown', function (e) {
switch(e.keyCode){
case 229:
case 0:
if($(this).val() == '')
$(this).prev().focus();
break;
}
});
The same can be achieved by checking the characters, of course this will only be in the case of a backspace in the android keyboard device, is just a workaround, hope it helps.

Capture key press without placing an input element on the page?

How to capture key press, e.g., Ctrl+Z, without placing an input element on the page in JavaScript? Seems that in IE, keypress and keyup events can only be bound to input elements (input boxes, textareas, etc)
For non-printable keys such as arrow keys and shortcut keys such as Ctrl-z, Ctrl-x, Ctrl-c that may trigger some action in the browser (for instance, inside editable documents or elements), you may not get a keypress event in all browsers. For this reason you have to use keydown instead, if you're interested in suppressing the browser's default action. If not, keyup will do just as well.
Attaching a keydown event to document works in all the major browsers:
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.ctrlKey && evt.keyCode == 90) {
alert("Ctrl-Z");
}
};
For a complete reference, I strongly recommend Jan Wolter's article on JavaScript key handling.
jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:
$(document).keypress(function(e){
var checkWebkitandIE=(e.which==26 ? 1 : 0);
var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);
if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});
Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064
Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:
$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
$("body").append("<p>ctrl+z detected!</p>");
});
For modern JS, use event.key!
document.addEventListener("keypress", function onPress(event) {
if (event.key === "z" && event.ctrlKey) {
// Do something awesome
}
});
NOTE: The old properties (.keyCode and .which) are Deprecated.
Mozilla Docs
Supported Browsers
Detect key press, including key combinations:
window.addEventListener('keydown', function (e) {
if (e.ctrlKey && e.keyCode == 90) {
// Ctrl + z pressed
}
});
Benefit here is that you are not overwriting any global properties, but instead merely introducing a side effect. Not good, but definitely a whole lot less nefarious than other suggestions on here.
Code & detects ctrl+z
document.onkeyup = function(e) {
if(e.ctrlKey && e.keyCode == 90) {
// ctrl+z pressed
}
}
Attach a listener to the keydown event instead of keypress, since the latter is now deprecated.
window.addEventListener('keydown', keyDownHandler);
The keydown event triggers continuously while the key is pressed. If you wanna have it fire only once, inside the handler use the event.repeat property as so:
keyDownHandler(event) {
if (!event.repeat) {
<code here will only be executed once while the key is pressed>
}
}
Remember to remove the listener when not needed anymore.
window.removeEventListener('keydown', keyDownHandler);

Categories

Resources