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:
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
[tabindex] {
7
outline: none; /* only to disable outline on focusable elements */
8
}
9
10
</style>
11
<script>
12
13
function isApple() {
14
var expression = /(Mac|iPhone|iPod|iPad)/i;
15
return expression.test(navigator.platform);
16
}
17
18
function isControl(event) { // Returns true if Ctrl or cmd keys were pressed.
19
if (isApple()) {
20
return event.metaKey;
21
}
22
return event.ctrlKey; // Windows, Linux, UNIX
23
}
24
25
function isSelecting(event) { // Returns true if Ctrl+a or cmd+a were pressed (all text selection).
26
if (isControl(event)) {
27
return event.key === 'a';
28
}
29
return false;
30
}
31
32
</script>
33
</head>
34
<body>
35
<div id="my-element" tabindex="0">
36
Click on this text and press Ctrl+a or cmd+a keys.
37
</div>
38
<script>
39
40
var element = document.querySelector('#my-element');
41
42
element.addEventListener('keydown', function(event) {
43
if (isSelecting(event)) {
44
console.log('Ctrl+a or cmd+a keys pressed!');
45
}
46
});
47
48
</script>
49
</body>
50
</html>
Hint: to handle
keydown
event ondiv
or other HTML element it is necessary to addtabindex="0"
attribute to the element.