Languages
[Edit]
EN

JavaScript - detect when ctrl key was pressed

0 points
Created by:
Rubi-Reyna
677

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

Quick solution:

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

 

1. Practical example

In this example, we use ctrlKey property to detect if the Ctrl key was pressed.

// ONLINE-RUNNER:browser;

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

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

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

2. Ctrl + another key

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

// ONLINE-RUNNER:browser;

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

    window.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key == 'q') {
          console.log('Ctrl + q pressed');
        }
    });

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

3. Ctrl + mouse click

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

// ONLINE-RUNNER:browser;

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

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

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

See also

  1. JavaScript - keyboard events

  2. JavaScript - mouse events

References

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

Alternative titles

  1. JavaScript - detect when ctrl key was pressed with another key
  2. JavaScript - detect when key was pressed while holding ctrl key
  3. JavaScript - detect when control key was pressed
  4. JavaScript - detect when control key was pressed with another key
  5. JavaScript - detect when key was pressed while holding control 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