In this tutorial we will learn How to Detect Shift Key Press with JavaScript. We can use keydown event along with JavaScript keyCode property and which property to detect if the shift key is pressed or not.
Table of Contents
keydown event
keydown event is fired when the keyboard key is pressed which can further execute a function.
keyCode property
keyCode property returns the key code or unicode of the keyboard key which has triggered the event.
which property
which property also returns the key code or unicode of the keyboard key that triggers the event.
IE8 and earlier versions of Internet Explorer don't support which property that is why we can use both to increase the cross browser compatibility of our code.
JavaScript Code
Take a look at the JavaScript code, 16 is the keycode of shift key that is why the keycode of the pressed key is compared with it and if the comparison returns true then alert message is displayed.
<script>
document.addEventListener("keydown", function(){
var x = event.keyCode || event.which;
if(x==16)
{
alert ("Shift Key is Pressed");
}
});
</script>
Demo
Video Tutorial
Watch video tutorial on How To Detect Shift Key Press using JavaScript.