Keycode and Charcode

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's which property. Most but not all of these browsers also store the character code in the charCode property.
  • In the keypress event, IE <= 8 stores the character code in the keyCode 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.

How do you convert a Javascript keyCode to a charCode?

I just want to say, this question became a fun learning adventure. But....

You're using deprecated APIs.

As it turns out KeyboardEvent.keyCode has been deprecated for a while. Because it uses the decimal version of ASCII. The correct code to use is actually event.Code. But that's not what you're after.

To get the ascii number, you can just use event.key.charCodeAt() This does have some flaws as it will report S when you hit shift. But you can use event.location to figure out if the key is a special control key. Zero is standard keys and 1-3 are special locations (I think).

document.addEventListener("keyup", function(e) {

document.querySelector(".key").innerHTML = e.key;
document.querySelector(".keyCode").innerHTML = e.code;
document.querySelector(".ascii").innerHTML = e.key.charCodeAt()
document.querySelector(".UTF").innerHTML = String.fromCharCode(event.key.charCodeAt());

});
code {
background-color: #e2aec8ab;
;
border: solid 1px gray;
border-radius: 3px;
padding: 0 .5em;
min-height: 1em;
min-width: .2em;
margin: 0 .1em;
}

.output {
margin: 2em;
border: solid 1px lightgray;
border-radius: 3px;
background-color: rgba(200, 250, 230, .3);
padding: 1em;
}
Type here. Try some alpha letters as well as special keys like <code>`</code>
<code>-</code>
<code>=</code>
<code>[</code>
<code>]</code>
<code>[ENTER]</code>
<code>;</code>
<code>'</code>

<div class="output">
You typed <code class="key"></code> which is Javascript <b>keyCode</b> <code class="keyCode"></code>, in ASCII that would be <code class="ascii"> </code> which is <code class="UTF"></code>
</div>

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 does this syntax mean: ? event.charCode : event.keyCode;

This is called the ternary operator. It's a short if...else statement.

Basically, your code can be expanded to this.

var chCode;

if ('charCode' in event) {
chCode = event.charCode;
} else {
chCode = event.keyCode;
}

event.keyCode and charCode on safari gives undefined for german special signs

keyCode is the only property you need in keyup and keydown events. It works in all major browsers, including Safari. Here's a better version of your function. I'm not sure if there's another problem or not; let me know if there is.

function onKeyUpHandler(e) {
e = e || window.event;
var code = e.keyCode;
if (code < 37 || code > 40) { // not arrows
//do Stuff;
}
}

Here is what I consider the definitive page on JavaScript key events: http://unixpapa.com/js/key.html

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.

.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).

Changing the charCode of the key pressed

You can't override the keycode in the event object...

Look at this snippet:

$('#target').keypress(function(e){
if (e.which == 97)
this.value = this.value + String.fromCharCode(98)
else
this.value = this.value + String.fromCharCode(e.which)

....

return false;
})


Related Topics



Leave a reply



Submit