CancelImage Upload

How to detect when the shift key is pressed with JavaScript

If you are programming a fancy typing interface for your web application you will without a doubt need to find out when a user has actually pressed the shift key. It's the only way after all for your application to then decide when to type small or large letters.

In JavaScript the shift key detection can take place after any kind of event. Ideally this event would be onkeypress. If pressed the following code will return true:

event.shiftKey

Here then is how the above code can be called upon through a onkeypress event. If the shift key is held down while a normal key on your keyboard is pressed, you will see the message The shift key was pressed. Otherwise you will read The shift key was NOT pressed.

<html>
<head>
<title>How to detect when the shift key is pressed with JavaScript</title>
<script type="text/javascript">

function getKeys(event)
{

         var status = document.getElementById("status");

         if(event.shiftKey)
         {

                  status.innerHTML = "The shift key was pressed!";

         }
         else
         {

                  status.innerHTML = "The shift key was NOT pressed!";

         }

}

</script>
</head>
<body onkeypress="javascript:getKeys(event);">

<span id="status"></span>

</body>
</html>


Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com