EN
JavaScript - event on Ctrl+a or cmd+a keys pressed
12
points
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 ondiv
or other HTML element it is necessary to addtabindex="0"
attribute to the element.