JavaScript KeyCode vs CharCode
The answers to all your questions can be found on the following page.
...but in summary:
- The only event from which you can reliably obtain character information (as opposed to key code information) is the
keypress
event. - In the
keypress
event, all browsers except IE <= 8 store the character code in the event'swhich
property. Most but not all of these browsers also store the character code in thecharCode
property. - In the
keypress
event, IE <= 8 stores the character code in thekeyCode
property.
This means to get the character code corresponding to the keypress, the following will work everywhere, assuming a keypress event object is stored in a variable called e
:
var charCode = (typeof e.which == "number") ? e.which : e.keyCode
This will generally return you a character code where one exists and 0 otherwise. There are a few cases where you'll get a non-zero value when you shouldn't:
- In Opera < 10.50 for keys Insert, Delete, Home and End
- In recent versions of Konqueror for non-character keys.
The workaround for the first problem is a little involved and requires using the keydown
event as well.
.keyCode vs. .which
Note: The answer below was written in 2010. Here many years later, both keyCode
and which
are deprecated in favor of key
(for the logical key) and code
(for the physical placement of the key). But note that IE doesn't support code
, and its support for key
is based on an older version of the spec so isn't quite correct. As I write this, the current Edge based on EdgeHTML and Chakra doesn't support code
either, but Microsoft is rolling out its Blink- and V8- based replacement for Edge, which presumably does/will.
Some browsers use keyCode
, others use which
.
If you're using jQuery, you can reliably use which
as jQuery standardizes things; More here.
If you're not using jQuery, you can do this:
var key = 'which' in e ? e.which : e.keyCode;
Or alternatively:
var key = e.which || e.keyCode || 0;
...which handles the possibility that e.which
might be 0
(by restoring that 0
at the end, using JavaScript's curiously-powerful ||
operator).
Javascript String.charCodeAt(index) and keyCodes
string.charCodeAt(index) is designed to return you the ascii value for the character of a string at a specified position.
keyCode is the browser implementation of what the value for the keyboard key that was pressed. unfortunately, it's not standardized across all browsers either.
Edit:
String.fromCharCode(unicodeValue);
This will convert a unicode value such as keyCode into an ascii value. Just be mindful that not all keyCode values are going to convert to an appropriate ascii value (since there isn't one) such key presses like { delete, up, down, left, right, home, insert, page up, page down }
Example: pressing the Delete key returns a keyCode of 46, if you do alert(String.fromCharCode(46));
you will see it output a period since the 46 is the ascii value for a period.
event.keycode vs event.which
Some browsers use keyCode
and others use which
. But with jQuery this is normalized so you don't have to think about that. You can just choose the one you prefer.
KeyboardEvent.keyCode deprecated. What does this mean in practice?
You have three ways to handle it, as it's written on the link you shared.
if (event.key !== undefined) {
} else if (event.keyIdentifier !== undefined) {
} else if (event.keyCode !== undefined) {
}
you should contemplate them, that's the right way if you want cross browser support.
It could be easier if you implement something like this.
var dispatchForCode = function(event, callback) {
var code;
if (event.key !== undefined) {
code = event.key;
} else if (event.keyIdentifier !== undefined) {
code = event.keyIdentifier;
} else if (event.keyCode !== undefined) {
code = event.keyCode;
}
callback(code);
};
How to know if a key is pressed having no charcode value
Vanilla JavaScript:
For other constants, see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent
window.onkeydown = function (e) {
switch (e.keyCode) {
case KeyboardEvent.DOM_VK_SPACE:
alert('space bar!');
break;
case KeyboardEvent.DOM_VK_CAPS_LOCK:
alert('CAPS LOCK!');
break;
case KeyboardEvent.DOM_VK_CONTROL:
alert('control!');
break;
case KeyboardEvent.DOM_VK_SHIFT:
alert('shift!');
break;
case KeyboardEvent.DOM_VK_ALT:
alert('alt!');
break;
}
};
UPDATED FOR REQUIREMENT TO AVOID CASES:
Per the following test, the only numeric values that will, after trimming (and not including numbers not corresponding to the average keyboard), be reduced to an empty string are 9,10,11,12,13,32. Looking at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Virtual_key_codes , the only ones that correspond are tab, clear, return, and space .
// Run in Firefox where trim() is supported (without need for jQuery):
var arr = [];
for (var i=0; i < 0xFFFF; i++) {
if (String.fromCharCode(i).trim() == '') {
arr.push(i);
}
}
In other words, your own test is not going to catch all cases.
So you have to use numeric comparisons based on the info at https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Virtual_key_codes and BASED ON EXACTLY WHAT CHARACTERS YOU NEED TO INCLUDE (or exclude).
For example, if you consider the cancel key, help key, back space, tab, etc. all to be of the type you mentioned, you can do:
window.onkeydown = function (e) {
if (e.keyCode < 0x30) {
alert('Special key pressed!');
}
};
As you can see, this allows for us to find a whole group of characters within a short amount of code (e.g., without using case). (But if we don't know exactly which characters you want to include or exclude, we can't give you a more precise answer.)
what is the difference between e.keyCode and e.which?
The event.which property normalizes event.keyCode and event.charCode.
It is recommended to watch event.which for keyboard key input.
As per JQuery documentation
keyCode is standard JavaScript and of course not implemented in the same way by all browsers.
keypress and keyup - why is the keyCode different?
The events are for completely different purposes. Use keyup
and keydown
for identifying physical keys and keypress
for identifying typed characters. The two are fundamentally different tasks with different events; don't try to mix the two. In particular, keyCode
on keypress
events is usually redundant and shouldn't be used (except in older IE, but see the linked document below for more on that); for printable keypresses it's usually the same as which
and charCode
, although there is some variation between browsers.
Jan Wolter's article on key events, already linked to in another answer, is the definitive word on this subject for me and has tables describing what each of the different properties returns for each type of key event and each browser.
Javascript keycode =/= charcode
Well, like I said in comments, the goal behind this question was to filter a textbox on numeric values. I managed to reach my goal using the keypress event.
I've published a jQuery plug-in for those who are interested in the solution.
Related Topics
How to Get All Arguments of a Function as Single Object Inside That Function
Embed a JavaScript Engine in an iOS Application
Uint8Array to String in JavaScript
How to See Ping Pong in Web Socket in iOS
How to Get Objects Value If Its Name Contains Dots
Ruby on Rails 4 JavaScript Not Executed
Passing a Function with Parameters as a Parameter
How to Add/Remove a Class in JavaScript
Resize Svg When Window Is Resized in D3.Js
Converting JSON Format to CSV to Upload Data Table in R to Produce D3 Bubble Chart
Clear Text Selection with JavaScript
How to Pass Parameters in Get Requests with Jquery
Safari Web Extension - Injecting Script Only When Extension Button Is Clicked
JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable
How to Obtain the Query String from the Current Url with JavaScript