EN
JavaScript - detect when ctrl key was pressed
0 points
In this article, we would like to show you how to detect when the CTRL key was pressed using JavaScript.
Quick solution:
xxxxxxxxxx
1
element.addEventListener('keydown', function(e) {
2
if (e.ctrlKey) {
3
console.log('CTRL key pressed');
4
}
5
});
In this example, we use ctrlKey
property to detect if the Ctrl
key was pressed.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here and press CTRL key.</div>
5
<script>
6
7
document.addEventListener('keydown', function(e) {
8
if (e.ctrlKey) {
9
console.log('CTRL key pressed');
10
}
11
});
12
13
</script>
14
</body>
15
</html>
In this example, we present how to detect when q
key was pressed while holding the Ctrl
key.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here and press Ctrl + q.</div>
5
<script>
6
7
window.addEventListener('keydown', function(e) {
8
if (e.ctrlKey && e.key == 'q') {
9
console.log('Ctrl + q pressed');
10
}
11
});
12
13
</script>
14
</body>
15
</html>
In this example, we present how to detect when the left mouse button was clicked while holding the Ctrl
key.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here, hold Ctrl key and click with your mouse.</div>
5
<script>
6
7
window.addEventListener('click', function(e) {
8
if (e.ctrlKey && e.which == 1) {
9
console.log('Left mouse button pressed while holding Ctrl');
10
}
11
});
12
13
</script>
14
</body>
15
</html>
Alternative titles
- JavaScript - detect when ctrl key was pressed with another key
- JavaScript - detect when key was pressed while holding ctrl key
- JavaScript - detect when control key was pressed
- JavaScript - detect when control key was pressed with another key
- JavaScript - detect when key was pressed while holding control key