Detect Shift Key Press with JavaScript

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.

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.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color