Contact!

Detect single and multiple keypress events: JavaScript

Detecting Keypress JavaScript

I used to just make websites and it made me completely ignorant to the importance of listening to keypress events in JavaScript. In truth, I didn’t ever have the need to handle multiple keypresses. Now that I have moved into app, gui and game development getting the keypresses right has become a lot more important.

The first thing I would like to say on the subject is not to use the ‘keypress’ event. This feature has been deprecated and gives you less control. I personally use ‘keydown’ and ‘keyup’ events instead.

Listening for a single key press

A ‘keydown’ event listener looks like this:

document.addEventListener('keydown', (event) => {
    // do something
});

When we use a ‘keydown’ event we are listening for the moment when a key is pressed. We can similarly react when a key is released using the ‘keyup’ event.

document.addEventListener('keyup', (event) => {
	// do something
});

Listening to elements for more specific focus

The above example is attached to the document. It is important to understand that where we attach the listener changes the behaviour. By attaching it to a more specific element we can localise key events and behaviours to when the element contains focus-within.

<div id="box">
    <input type="text">
</div>

<script>
    document.getElementById('input').addEventListener('keydown', (event) => {
        alert('inside box');
    });
</script>

Notice that within the above example our ‘keydown’ event doesn’t fire when our focus is within the document, but does when we are in the input.

Checking which key has been pressed

At the moment our ‘do something’ code will fire on every key press. More commonly it is likely that we want to tie the ‘do something’ to a specific key press. This is why it is important to make the ‘event’ object available within our function. From within the ‘event’ object we can use ‘event.key’ to identify the specific key value that was pressed.

document.addEventListener('keyup', (event) => {
    if (event.key == 'ArrowUp') {
        // do something
    }
});

It is worth noting that when using ‘event.key’ we get the value of the key pressed. This means that when using a shift modifier the returned alphabetical character will be uppercase, or any modified character such as an @ symbol.

Listening for multi-key presses / creating modifiers

So what happens when we want to listen to 2 keys being pressed at the same time? Having a modifier key is quite a common scenario and used for the vast majority of keyboard shortcuts in applications.

The answer is to add an object to catch the key presses.

let keysPressed = {};

document.addEventListener('keydown', (event) => {
   keysPressed[event.key] = true;
});

When a key is pressed we add the value as the object key and set it to true. We now have a flag to tell us when certain key values are active. Next we make sure that we clear the key values when ‘keyup’ is triggered.

document.addEventListener('keyup', (event) => {
    delete this.keysPressed[event.key];
 });

Finally we can check for multiple keys with simple statements.

document.addEventListener('keydown', (event) => {
   keysPressed[event.key] = true;

   if (keysPressed['Control'] && event.key == 'a') {
       alert(event.key);
   }
});

document.addEventListener('keyup', (event) => {
   delete keysPressed[event.key];
});
  1. qqqq says:

    hmmmm…………

  2. dsafafasfdf says:

    YO THIS STUFF IS AWESOME !!

  3. 李大雷 says:

    Brilliant!

  4. riko says:

    U have made my day.

  5. Yuri says:

    Fair enough, i agree.

  6. Mukesh Aravinth says:

    But if a key is continously pressed, there would be multiple key down events and when the key is released, there would be only one key up event, right ?

    if we go with this approach

  7. Sebastian says:

    Nice!

  8. David Maia says:

    Delete is terrible on performance. Just set the value to false

  9. sergey says:

    Just what I was looking for. Thanks for the info here!

  10. samad says:

    Your cookies are very Yummy..

  11. Gg says:

    This will stop working correctly once user will press a key, change browser tab, release key, and then get back to your application tab.
    Your code will still “think” that which is already release, is still pressed.

  12. a failure says:

    In the example does control have to be pressed before?

  13. Veronica Holguin says:

    Bueno si

Join the discussion!

You might like:

Create, register and use shortcodes in WordPress

Create, register and use shortcodes in WordPress

by Gav 18/03/2023

Learn how to create and register your own WordPress shortcodes to add dynamic content to your posts and pages.

How to use guard clauses in JavaScript

How to/why use guard clauses in JavaScript

by Gav 16/03/2023

Learn how to improve code readability and performance by using guard clauses in JavaScript. Discover their benefits and best practices.

Implements and Extends, Object Oriented TypeScript

Implements and Extends, Object Oriented TypeScript

by Gav 15/03/2023

Learn the difference between implements and extends in TypeScript. Use Implements to implement interfaces and types, and extends to inherit from classes.

Reading/Parsing and Writing YAML files in PHP, Symfony

Reading/Parsing and Writing YAML files, PHP Symfony

by Gav 14/03/2023

In this tutorial we will look at using YAML in PHP. Learn about Parsing and Writing YAML files using Symfony's YAML component.

Measuring code execution performance in JavaScript

Measuring code execution performance in JavaScript

by Gav 13/03/2023

Measuring code execution performance is an important way to identify bottlenecks. Use these methods in JavaScript to help optimise your code.

Measuring script/code execution time in PHP using microtime

Measuring script/code execution time in PHP, microtime

by Gav 06/03/2023

Find bottlenecks, optimise and clean your code, and speed up your apps by measuring the execution time of your PHP scripts using microtime.

Regenerate WordPress media image sizes, programmatically

Regenerate WordPress media image sizes, programmatically

by Gav 25/02/2021

Learn how to regenerate and update WordPress media and image sizes both programmatically (without plugin), and also with a handy plugin.

Magic Constants in PHP. What they are and how to use them.

Magic Constants in PHP. What they are and how to use them

by Gav 15/02/2021

Ever seen constants like __DIR__ and __FILE__ being used in PHP? These are 'Magic Constants', and this is how we can use them.

Detecting Keypress JavaScript

Detect single and multiple keypress events: JavaScript

by Gav 16/10/2019

Learn how to use event listeners to detect and handle single and multiple keypress events in JavaScript. Add modifier keys to your application!