- How do I detect keypresses in Javascript?
- 6 Answers 6
- Adding keyboard input events in JavaScript
- Keyboard event types
- Handling keyboard events
- From keyboard event to output
- Summary
- Detect Keyboard Input Event in JavaScript
- Detect Keyboard Input Event Using addEventListener() in JavaScript
- Syntax
- Parameter
- Related Article - JavaScript Event
How do I detect keypresses in Javascript?
After looking around on the internet, I’ve seen a lot of suggestions (use window.onkeypress, use jQuery, etc.) but for almost every option there’s a counterargument. How can I detect a keypress in Javascript?
I’d suggest just listening for the keypress event, or possibly one of it’s counterparts (keydown or keyup)
jQuery is JavaScript; the only difference is that jQuery is a library that abstracts away cross-browser differences, to make it easier (but not necessarily more efficient) to write cross-browser code.
6 Answers 6
With plain Javascript, the simplest is:
document.onkeypress = function (e) < e = e || window.event; // use e.keyCode >;
But with this, you can only bind one handler for the event.
In addition, you could use the following to be able to potentially bind multiple handlers to the same event:
addEvent(document, "keypress", function (e) < e = e || window.event; // use e.keyCode >); function addEvent(element, eventName, callback) < if (element.addEventListener) < element.addEventListener(eventName, callback, false); >else if (element.attachEvent) < element.attachEvent("on" + eventName, callback); >else < element["on" + eventName] = callback; >>
In either case, keyCode isn’t consistent across browsers, so there’s more to check for and figure out. Notice the e = e || window.event — that’s a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.
$(document).on("keypress", function (e) < // use e.which >);
Other than jQuery being a «large» library, jQuery really helps with inconsistencies between browsers, especially with window events. and that can’t be denied. Hopefully it’s obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it’s a little harder to know unless you do everything that the jQuery library internally does.
Note there is a keydown event, that is different than keypress . You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown
As for suggesting what to use, I would definitely suggest using jQuery if you’re up for learning the framework. At the same time, I would say that you should learn Javascript’s syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what’s happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it’s Javascript, and wraps the language.
Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don’t have to worry.
Here’s something that might help decide:
Adding keyboard input events in JavaScript
In some circumstances, you may want to add keyboard input events to your web page or app, such as when numeric input is required to make a calculation or for gaming.
Though it is a fairly straightforward process, there are several deprecated methods that can make the implementation of keyboard input problematic.
In this tutorial, we show you the right ways to add keyboard events to your web page or app in 2022.
Keyboard event types
To incorporate keyboard events, listen out for one of the following on the document object:
- keydown : fires when a key is pressed, provides code of key pressed
- keypress : fire when a key is pressed, provide code of which character is intended
- keyup : fired when a pressed down key is released
Example: If shift + a is pressed for in a keydown event, the printed value of .key will be Shift and A . For a keypress event, is will only print A .
Each time a key is pressed, an event object is generated. You can check out these objects with the following code:
document.addEventListener('keydown', (event) => < console.log(event); >);
If you run this code and open the console log in your browser, the output will look something like this after some keys are pressed:
These objects provide us with the necessary information to handle each key press. For example, you can see that the key and code property indicate the key pressed.
Now, we need to respond to this input.
Handling keyboard events
In each object generated by a key press, there are two properties you may want to use:
- event.key : the logical value of the key pressed
- event.code : based upon the physical position of the keys
We can see the values generated by pressing keys with the following code:
document.addEventListener('keydown', (event) => < console.log("event.key = " + event.key + " " + "event.code wp-block-image size-full">![]()
Notice that
event.key
andevent.code
generally match, but not always. The final two outputs were generated by pressing#
and+
. Butevent.code
registered the values for these events asBackslash
andBracketRight
.This is because the value of
event.code
is generated based on the physical placement of a key. Thus, it can often produce unintuitive results across different keyboard layouts.For more predictable results,
event.key
is recommended.The previously usedevent.which
andevent.keyCode
properties have been deprecated. Their use is therefore not guaranteed to be supported by modern browsers.From keyboard event to output
A simple way to handle the output is to append the
event.key
value to the DOM:document.addEventListener('keydown', (event) => < document.body.append(event.key); >);But is most situations, this is too simplistic. We instead need to specify what should have in response to a key press with a specific value, rather than using the value directly.
For example, when creating a JavaScript calculator, it would be undesirable for letters to be displayed.
Therefore, in most situations, it is a good idea to handle valid key presses inside an if. else statement:
document.addEventListener('keydown', (event) => < if (event.key == "0") else if (event.key == "1") else if (event.key == "2") else if (event.key == "3") else if (event.key == "4") else if (event.key == "5") else if (event.key == "6") else if(event.key == "7") else if(event.key == "8") else if(event.key == "9") else if(event.key == "+") else if(event.key == "-") else if(event.key == "*") else if(event.key == "/")>); By handling each valid keyboard input in this way, non-valid keyboard input is ignored by default. So, in the above example, only the numbers 0-9 and + , - , * and / are appended to the DOM. Letters, for example, are not handled.
Summary
Adding keyboard events to your web page or app can greatly improve user experience, such as when input is required for a numeric calculation or for gaming.
Detect Keyboard Input Event in JavaScript
An event listener is simply a JavaScript function that’s triggered when a particular user input event happens. A simple example of such an event is a mouse click or keyboard button press. Event listener functions have to be first registered with a target. After that, whenever a particular event we’re interested in happens, our listener function is triggered. Multiple listeners can be attached to the same target that can listen to the same or different event types.
Today’s post shows you how to recognize keyboard input events in JavaScript.
Detect Keyboard Input Event Using addEventListener() in JavaScript
This is a built-in method provided by JavaScript that registers an event listener. It is a method of the EventTarget interface. Whenever the specified event is detected on the target, our function that is configured is called.
Syntax
target.addEventListener($type, $listener); target.addEventListener($type, $listener, $options); target.addEventListener($type, $listener, $useCapture);
Parameter
- $type : It is a mandatory parameter that only accepts a string that specifies the type of event to be listened to. It is case sensitive and supports various events like mouse , keyboard , input , database , etc.
- $listener : It is a mandatory parameter, an object that will receive a notification when an event of the specified type occurs. This object must be implementing the EventListener interface or a JavaScript function.
- $options : It is an optional parameter that specifies the characteristics of the event listener. Some of the characteristics are capture , once , passive , and signal .
- $useCapture : It is an optional parameter that accepts Boolean values indicating whether events of this type are sent to the registered listener before being sent to an EventTarget below in the DOM tree.
There are three types of keyboard events that you can listen to keydown , keypress , and keyup . The browser fires a keydown event, when a key on the keyboard is pressed, and when it is released, a keyup event fires. Each Keyboard event has its own keyCode or key . For eg, Enter button has key Enter and keyCode 13 .
document.getElementById("textId").addEventListener("keydown", myFunction); function myFunction() switch (event.key) case "ArrowDown": console.log("ArrowDown"); break; case "ArrowUp": console.log("ArrowUp"); break; case "ArrowLeft": console.log("ArrowLeft"); break; case "ArrowRight": console.log("ArrowRight"); break; default: console.log(event.key, event.keyCode); return; > event.preventDefault(); >
Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.