For example, if i have this:
<input type='text' onkeydown='doSomething()' />
<script>
function doSomething() {
// ?
}
</script>
i need to get the keyCode/character pressed in cross-browser/os way.. how to do it? i've tried about this ~6 years ago and as i remember that time, it was not easy, sometimes i must pass event or something to get it work on opera or IE cmiiw
Definition and Usage. Note: The keyCode property is deprecated. Use the key property instead.
Keycode 13 is the Enter key.
KeyCode was deprecated because in practice it was “inconsistent across platforms and even the same implementation on different operating systems or using different localizations.” The new recommendation is to use key or code .
Detecting keys in JavaScriptdocument. onkeydown = function (e) { console. log('key down'); console. log(e); };
You're close, but the issue with your code is you're executing doSomething()
in response to keyDown
events... let's look closely — you're executing doSomething
without passing any arguments in. You're also not naming/accepting arguments, even if you did pass them.
A few quick tweaks to your code and you're all set:
// Notice an `event` argument, containing the important data
function doSomething(event) {
console.log('****** doSomething');
console.log('event.keyCode: ', event.keyCode);
console.log('event.which: ', event.which);
console.log('event.key: ', event.key);
console.log('event.code: ', event.code);
}
<!-- Notice: We pass the key `event` object into doSomething -->
<input type='text' onkeydown='doSomething(event)' placeholder="Type here..." />
I'm confused on this too, but let's review the options. Get ready for some 1995-esque browser differences!
First, keep in mind that while the end goal may be to determine what key was pressed, different methods require different steps to arrive at that. An event can either be a "system and implementation dependent numerical code", a Unicode char value, the Ascii value, or the actual key name ("ArrowUp").
event.key
(TL;DR: Try to use this)According to MDN KeyboardEvent.key
Documentation, event.key
is the recommended way if you're looking for the non-deprecated, "future-forward" way. Documentation is under heavy modification though, so details are sparse on MDN.
Looking at the caniuse.com support table for event.key
, there's no support below IE11 or on Safari at all (as of Jan 2017). That may already be a deal-breaker, so let's keep looking.
event.keyCode
I've always used event.keyCode
, which MDN says is now deprecated and comes with this warning:
You should avoid using this if possible; it's been deprecated for some time. Instead, you should use
KeyboardEvent.code
, if it's implemented. Unfortunately, some browsers still don't have it, so you'll have to be careful to make sure you use one which is supported on all target browsers. Google Chrome and Safari have implementedKeyboardEvent.keyIdentifier
, which was defined in a draft specification but not the final spec.
Alright, fair enough — there's enough differences between browsers and subtle differences between keydown
and keypress
events (not the same thing!) to make this not worth using any more. RIP keyCode
, it's been real!
event.which
From MDN docs:
The numeric code for a particular key pressed, depending on whether an alphanumeric or non-alphanumeric key was pressed. Please see KeyboardEvent.charCode** and KeyboardEvent.keyCode for more details.
Another one in the process of deprecation — "This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped."
Ok, well keyCode
we already know is deprecated too, so what's charCode
about?
event.charCode
This returns the Unicode char code for a keypress
event... and we get another warning from MDN:
Do not use this property anymore, it is deprecated. Use
KeyboardEvent.key
instead.
Starting to chase our own tails here, KeyboardEvent.key
is the future-forward approach, but not yet adequately supported... it also returns 0
all the time for keydown
events, you must listen to keypress
events for this to be valuable.
event.code
The last option seems promising... event.code
docs from MDN:
represents a physical key on the keyboard (as opposed to the character generated by pressing the key). In other words, this property returns a value which isn't altered by keyboard layout or the state of the modifier keys.
This is handy because we get things like ShiftRight
versus ShiftLeft
, useful for game development and very specific interactions. There's a great chart at the bottom of the docs for all code options.
The catch: not very good support yet. Nothing on IE, iOS Safari, Android, or Opera.
TBH I don't think there's a one-size-fits all solution. The current landscape seems to require some degree of polyfilling, or at least supporting the old event.keyCode
and event.which
properties as fallbacks for where event.key
and event.code
can't be used.
For production projects, we just need to consider the browser and device support requirements and go from there.
There's a few extra properties to check if you care about other keys pressed in combination with the original key:
keycode.info
An invaluable tool for quickly figuring out what keyCode you need to write logic around is http://keycode.info/ (created by the v. cool Wes Bos)
...I've tried about this ~6 years ago...
In modern times...
document.querySelector('input').addEventListener(function(e) {
var key = e.keyCode || e.which;
...
});
Edit: Works in "modern" browsers, IE9+ and the rest of the crew.
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