EN
JavaScript - detect when alt key was pressed
0
points
In this article, we would like to show you how to detect when the alt key was pressed using JavaScript.
Quick solution:
element.addEventListener('keydown', function(e) {
if (e.altKey) {
console.log('alt key pressed');
}
});
1. Practical example
In this example, we use altKey property to detect if the Alt key was pressed.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Set focus here and press Alt key.</div>
<script>
document.addEventListener('keydown', function(e) {
if (e.altKey) {
console.log('Alt key pressed');
}
});
</script>
</body>
</html>
2. Alt + another key
In this example, we present how to detect when g key was pressed while holding the Alt key.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Set focus here and press Alt + g.</div>
<script>
window.addEventListener('keydown', function(e) {
if (e.altKey && e.key === 'g') {
console.log('Alt + g pressed');
}
});
</script>
</body>
</html>
3. Alt + mouse click
In this example, we present how to detect when the left mouse button was clicked while holding the Alt key.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<div>Set focus here, hold Alt key and click with your mouse.</div>
<script>
window.addEventListener('click', function(e) {
if (e.altKey && e.which == 1) {
console.log('Left mouse button pressed while holding Alt');
}
});
</script>
</body>
</html>