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:
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
References
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