Languages
[Edit]
EN

JavaScript - detect when left arrow key was pressed

0 points
Created by:
Brandy-Mccabe
754

In this article, we would like to show you how to detect when the left arrow key was pressed using JavaScript.

In the below solutions, we use some legacy functions that lets to get key code. The main reason why that approach was used, is the time when event.key and key.code were introduced in the major web browsers (around 2016-2017).

Practical examples

Both of the examples below provide the legacy support for the keyCode property which represents an integer value (37) of the left arrow key instead of a string (ArrowLeft).

Example 1

In this example, we use event.key to get the value of the key pressed by the user and then check if it's a left arrow.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Click here to get focus and press left arrow key.</div>
  <script>

    var MAPPING = {
        37: 'ArrowLeft',
    };

     function getKey(event) {
        return event.key || MAPPING[event.keyCode]; // with legacy support
    }

     document.addEventListener('keydown', function(event) {
        var key = getKey(event);
        if (key === 'ArrowLeft') {
            console.log('Arrow left pressed.');
        }
    });

  </script>
</body>
</html>

Example 2

In this example, we use event.code to get the value of the key pressed by the user and then check if it's a left arrow.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Click here to get focus and press left arrow key.</div>
  <script>

    var MAPPING = {
        37: 'ArrowLeft',
    };

    function getCode(event) {
        return event.code || MAPPING[event.keyCode]; // with legacy support
    }

    document.addEventListener('keydown', function(event) {
        var code = getCode(event);
        if (code === 'ArrowLeft') {
            console.log('Arrow left pressed.');
        }
    });

  </script>
</body>
</html>

See also

  1. JavaScript - detect when arrow key was pressed

References

  1. KeyboardEvent.key - MDN Docs
  2. KeyboardEvent.code - MDN Docs

  3. KeyboardEvent.keyCode - MDN Docs
  4. Document: keydown event - MDN Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join