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:
xxxxxxxxxx
1
element.addEventListener('keydown', function(e) {
2
if (e.shiftKey) {
3
console.log('shift key pressed');
4
}
5
});
In this example, we use shiftKey
property to detect if the shift key was pressed.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here and press Shift key.</div>
5
<script>
6
7
document.addEventListener('keydown', function(e) {
8
if (e.shiftKey) {
9
console.log('Shift key pressed');
10
}
11
});
12
13
</script>
14
</body>
15
</html>
In this example, we present how to detect when ArrowUp
key was pressed while holding the Shift
key.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here and press Shift + Arrow Up.</div>
5
<script>
6
7
window.addEventListener('keydown', function(e) {
8
if (e.shiftKey && e.key == 'ArrowUp') {
9
console.log('Shift + Arrow up 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 Shift
key.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<div>Set focus here, hold Shift key and click with your mouse.</div>
5
<script>
6
7
window.addEventListener('click', function(e) {
8
if (e.shiftKey && e.which == 1) {
9
console.log('Left mouse button pressed while holding Shift');
10
}
11
});
12
13
</script>
14
</body>
15
</html>