Detect CAPS lock is ON using JavaScript

JSHow to detect CAPS lock is ON using JavaScript?

If you have a secure page which requires the credentials which obvious is a case-sensitive. So in case if user is typing password without aware of if CAPS LOCK is ON, which will cause invalid credentials error .To avoid its better to show message to the end user that “CAPS LOCK is ON” by detecting┬áCAPS lock using JavaScript

Solution

We can avoid this kind of problems by just adding some JavaScript code to our page.

Script

//method to notify user if capslock is on
$("#password").keypress(function (e) {
 var keyCode = e.keyCode ? e.keyCode : e.which;
 var shiftKey = e.shiftKey ? e.shiftKey : ((keyCode == 16) ? true : false);
 if (((keyCode >= 65 && keyCode <= 90) && !shiftKey) || ((keyCode >= 97 && keyCode <= 122) && shiftKey))
 $("#caps_lock").show();
 else
 $("#caps_lock").hide();
});

HTML

<input type="password" name="txtPassword"/> 
<div id="caps_lock" style="font-weight: bold; display: none;">Caps Lock is ON</div>

Enjoy..!!

Leave a Reply

Your email address will not be published. Required fields are marked *