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