Languages
[Edit]
EN

JavaScript - detect when alt key was pressed

0 points
Created by:
Kevin
797

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

Quick solution:

element.addEventListener('keydown', function(e) {
    if (e.altKey) {
        console.log('alt key pressed');
    }
});

 

1. Practical example

In this example, we use altKey property to detect if the Alt key was pressed.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Set focus here and press Alt key.</div>
  <script>

    document.addEventListener('keydown', function(e) {
        if (e.altKey) {
          console.log('Alt key pressed');
        }
    });

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

2. Alt + another key

In this example, we present how to detect when g key was pressed while holding the Alt key.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Set focus here and press Alt + g.</div>
  <script>

    window.addEventListener('keydown', function(e) {
        if (e.altKey && e.key === 'g') {
          console.log('Alt + g pressed');
        }
    });

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

3. Alt + mouse click

In this example, we present how to detect when the left mouse button was clicked while holding the Alt key.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <div>Set focus here, hold Alt key and click with your mouse.</div>
  <script>

    window.addEventListener('click', function(e) {
        if (e.altKey && e.which == 1) {
          console.log('Left mouse button pressed while holding Alt');
        }
    });

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

See also

  1. JavaScript - keyboard events

  2. JavaScript - mouse events

References

  1. KeyboardEvent.altKey - Web APIs | MDN
  2. Document: keydown event - Web APIs | MDN

Alternative titles

  1. JavaScript - detect when alt key was pressed with another key
  2. JavaScript - detect when key was pressed while holding alt key
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