Languages
[Edit]
EN

JavaScript - event on Ctrl+a or cmd+a keys pressed

12 points
Created by:
Ela-Davey
663

In this short article, we would like to show how to handle Ctrl+a keys pressed event on Windows, Linux or Unix or cmd+a keys pressed on MacOS.

There is not available direct event that lets us to detect Ctrl+a or cmd+a keys, but if we are able to check pressed keys, it is simple to detect the action.

Quick solution:

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    [tabindex] {
        outline: none;  /* only to disable outline on focusable elements */
    }

</style>
<script>
  
  	function isApple() {
    	var expression = /(Mac|iPhone|iPod|iPad)/i;
        return expression.test(navigator.platform);
    }

    function isControl(event) { // Returns true if Ctrl or cmd keys were pressed.
        if (isApple()) {
            return event.metaKey;
        }
      	return event.ctrlKey; // Windows, Linux, UNIX
    }

  	function isSelecting(event) { // Returns true if Ctrl+a or cmd+a were pressed (all text selection).
    	if (isControl(event)) {
        	return event.key === 'a';
        }
      	return false;
    }

</script>
</head>
<body>
  <div id="my-element" tabindex="0">
    Click on this text and press Ctrl+a or cmd+a keys.
  </div>
  <script>
    
    var element = document.querySelector('#my-element');
    
    element.addEventListener('keydown', function(event) {
        if (isSelecting(event)) {
            console.log('Ctrl+a or cmd+a keys pressed!');
        }
    });
    
  </script>
</body>
</html>

Hint: to handle keydown event on div or other HTML element it is necessary to add tabindex="0" attribute to the element.

 

See also

  1. JavaScript - detect Apple device

  2. JavaScript - detect Ctrl key pressed 

Alternative titles

  1. JavaScript - event on Control+a or Command+a keys pressed
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