December 12th in Articles by .

Replicating Yahoo’s Caps Lock Indicator With jQuery


A while ago I wrote an article on using jQuery and plain JavaScript to add keyboard interaction to HTML forms. I then recently logged into one of Yahoo’s services and encountered their nifty caps lock indicator on the password field and thought I would replicate this using the code I wrote for the article mentioned above and some jQuery.

As usual we start of writing our HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
                <title>CapsDetector</title>
    </head>
    <body>
        <h1>CapsDetector</h1>
		<form name="capsdetector" id="capsdetector" action="" method="post">
			<fieldset>
				<legend>Enter your password:</legend>
				<label for="password">Password:</label><br />
				<input type="password" size="25" name="password" id="password" /><br />

				<input type="submit" value="Change Password" />
			</fieldset>
		</form>
    </body>
</html>

With out HTML in place we can move on to add our JavaScript interaction layer. Create a folder called javascript and download the following file into this folder. Once you have added the file you need to link this file as well as jQuery to your page so, add the following to the HTML’s head section:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script src="javascript/keyCodeMatcher.js" type="text/javascript"></script>

Here I am using Google’s Ajax API to load jQuery, this can be very useful on your site, especially is you experience high traffic loads. With these files loaded we are ready to add the needed code for our caps lock notifier. In the previous javascript folder add a new file called main.js. We first add a boolean variable flag to track whether the caps lock key has been pressed or not:

var _capsTriggered = false;

Next we add the usual jQuery ready code in which we will wrap the rest:

$(document).ready(function() {

});

Inside this we add our code to bind the keyup event to out password field:

$("#password").keyup(function(event) {

});

Now it’s time to create our function for detecting the caps lock key event and show our message. Outside the ready function add the following:

var capsDetector = function(event, message) {

	if (_capsTriggered == false) {
		if (getKeyCode(event) === 20) {
			var alertMessage = "<span id='capslock'>" + message + "</span>";
			$("#password").after(alertMessage);
			$("#capslock").fadeIn("slow");
			_capsTriggered = true;
		}
	} else if((_capsTriggered == true) && (getKeyCode(event) === 20)) {
		$("#capslock").fadeOut("slow");
		_capsTriggered = false;
	}
}

In the above code we first check our boolean flag to determine whether the caps lock key has been pressed and take the appropriate action. If the key has not yet been pressed the flag will be false and this means the current event is the first time the key is being pressed and we need to inform the user that they have pressed the caps lock key. The wrapping function takes two arguments, one being the actual event and the second the message we want to display to the user.

We first create a variable to hold the element we want to add to the page as well as the message passed. We then add the new DOM element after the input element and slowly fade it in, after which we set the boolean to true, indicating that the key has been pressed and our message is currently displayed to the user.

We next need to test for the alternative. In the else clause we first check to see whether the key has been pressed and then test the the current key being pressed is the caps lock key. Is we do not check for the second condition any other key pressed will remove the message. Seeing that the caps lock key has been pressed a second time we remove the DOM element and also set the flag to false so that the message will again be displayed on consecutive presses.

To bring this all together we need to make a call to our capsDetector method inside the keyup function we added earlier:

$("#password").keyup(function(event) {
	capsDetector(event, 'CapsLock key pressed! Passwords are case sensitive.');
});

With that we now have the functionality that will make all of this work. Our next step is to link our main JavaScript file to our HTML file. Add the following to the head of the document, after the other JavaScript imports:

<script src="javascript/main.js" type="text/javascript"></script>

To end off with we will add some simple styling to our added element. Create a folder called css and add a file called default.css. Next we need to link this CSS file to the HTML document. In the head of the document, before the JavaScript imports add the following line:

<link rel="stylesheet" href="css/default.css" type="text/css" media="screen">

Open up your CSS file and add the following:

#capslock
{
	display:none;
	background-color:#efff79;
	border:1px solid #333;
	margin:.5em;
	padding:.5em;
	font-size:90%;
	font-weight:bold;
	width:15em;
	/* CSS3 capable browser will rander rounded corners */
	border-radius:5px;
	/* Rounded corners for Gecko based browsers */
	-moz-border-radius:5px;
	/* Drop shadow for Gecko based browsers */
	-moz-box-shadow:3px 3px 5px #333;
	/* Drop shadow for Webkit based browsers */
	-webkit-box-shadow:#333 5px 5px 5px;
	/* Rounded corners for Webkit based browsers */
	-webkit-border-radius:5px;
}

Besides the basics I added three small block that will make the notification just a little more aesthetically pleasing. The comments pretty much explains what these will do but, in all honesty, if you are using the latest version of either Firefox or Chrome/Safari the Gecko and Webkit specific code, aside from the drop shadow, will not be required as it will recognize the CSS3 border-radius rule. That’s it! I believe that this is one of those small things that can be added to your site easily that will add another small layer of improved usability. Looking forward to your comments.

  • Graham

    I'm not sure there's much you can do about this,but the indicator is wrong if Caps Lock is on before the page loads. It displays the status backwards – warning the user when they turn it off and removing the warning when they turn it on.

    Otherwise, it's a cool trick and probably very useful :)

  • Graham

    I'm not sure there's much you can do about this,but the indicator is wrong if Caps Lock is on before the page loads. It displays the status backwards – warning the user when they turn it off and removing the warning when they turn it on.

    Otherwise, it's a cool trick and probably very useful :)

  • http://www.ossreleasefeed.com Schalk

    The idea here is not whether caps lock is active or not, it is more about whether the current key pressed is the caps lock key. I know I would have found it useful to know when I pressed the caps lock key even if it was not active initialy.

  • http://www.ossreleasefeed.com Schalk

    The idea here is not whether caps lock is active or not, it is more about whether the current key pressed is the caps lock key. I know I would have found it useful to know when I pressed the caps lock key even if it was not active initialy.

  • Julio Biason

    The demo doesn't seem to work on Firefox 3.5.5 on OS X.

    • http://www.ossreleasefeed.com Schalk

      I wonder whether the Mac has the same behavior here as with the ctrl key? I will have a look at this issue, thanks for letting me know.

      • Robin Card

        Works for me on Chrome mac.

  • Julio Biason

    The demo doesn't seem to work on Firefox 3.5.5 on OS X.

    • http://www.ossreleasefeed.com Schalk

      I wonder whether the Mac has the same behavior here as with the ctrl key? I will have a look at this issue, thanks for letting me know.

      • Robin Card

        Works for me on Chrome mac.

  • http://qalibrary.com/testing/functionl/the-practical-guide-to-defect-prevention/ Mathew Bascetta

    Really informative article, thank you for writing about this. You have a lot of well-done information on this site, thanks again! I found a brief primer on Software Testing, do you think it is any good? I’m curious about such introductory articles for someone who is thinking about getting into Testing. Visit my site if you’d like to read more.

  • http://qalibrary.com/testing/functionl/the-practical-guide-to-defect-prevention/ Mathew Bascetta

    Really informative article, thank you for writing about this. You have a lot of well-done information on this site, thanks again! I found a brief primer on Software Testing, do you think it is any good? I’m curious about such introductory articles for someone who is thinking about getting into Testing. Visit my site if you’d like to read more.

  • http://www.orstudents.org/forums/member/14122/ virus lab 2009

    This is a terrific little site, I can not believe I didn’t find it sooner

  • http://www.orstudents.org/forums/member/14122/ virus lab 2009

    This is a terrific little site, I can not believe I didn’t find it sooner

  • http://www.facebook.com/profile.php?id=1508375993 Darci Slager

    I appreciate this blog.

  • http://www.facebook.com/profile.php?id=1508375993 Darci Slager

    I appreciate this blog.

  • Johan

    if caps lock is set to on. on page load. then it can not catch caps lock

    • Anonymous

      Hi there Johan,

      Yes, that is unfortunately a limitation of JavaScript. Not the ideal solution, was more an exploration of how you would do that then anything else.

      Schalk

  • Sairam Bakthavatchalu

    Hi Schalk,
    It works fine for keypress :) can i get the same for onfocus of that particular Textbox ?

    When already Capslock has been activated and if we then focus on textbox it should work :) i think if we modify little i can get the desired but i am helpless :(

    • Anonymous

      Sairam, unfortunately we do not have access to the OS via the browser so we can only trap the keys as they are pressed. That is a definite limitation of the script but, it can be useful in some instances.

      If you do manage to make it more useful, please let me know ;)

  • http://www.facebook.com/nicktheandroid Nicholas Chamberlin

    This example and page is absolutely useless. It only notified you if you press the caps lock key while focused on the textbox. The whole point of checking for caps lock is so the user doesn’t think they’re entering their password in lowercase when they accidentally left caps lock on.. This example doesn’t accomplish anything useful.

    • Anonymous

      Unfortunately I have to agree but, as mentioned in an earlier reply, it is a limitation and was more an exploration of working with key presses in JavaScript than anything else. Thanks for your comment.

Performance Optimization WordPress Plugins by W3 EDGE