JavaScript: Detecting Caps lock
I wanted to see if you could detect caps lock in JavaScript. Why? As a small usability touch, basically alerting users that caps lock is enabled when they are entering passwords for example. I’ve wrapped up the logic in a simple function that can help you detect caps lock on a key press. Here is the demo and following is the function followed by a simple usage.
-
function isCapslock(e){
-
-
e = (e) ? e : window.event;
-
-
var charCode = false;
-
if (e.which) {
-
charCode = e.which;
-
} else if (e.keyCode) {
-
charCode = e.keyCode;
-
}
-
-
var shifton = false;
-
if (e.shiftKey) {
-
shifton = e.shiftKey;
-
} else if (e.modifiers) {
-
shifton = !!(e.modifiers & 4);
-
}
-
-
if (charCode >= 97 && charCode <= 122 && shifton) {
-
return true;
-
}
-
-
if (charCode >= 65 && charCode <= 90 && !shifton) {
-
return true;
-
}
-
-
return false;
-
-
}
-
-
<input type="text" name="testinput" id="testinput" value="" />
-
-
<script type="text/javascript">
-
-
document.getElementById(’testinput’).onkeypress = function(e){
-
-
if(isCapslock(e)){
-
-
alert("Caps on");
-
-
} else {
-
-
alert("Caps off");
-
-
}
-
-
}
-
-
</script>
-
Tags: events, JavaScript, keypress

July 12th, 2008 at 2:40 pm
Great blog, subscribed to your rss feed. Thanks.