Snippit Tutorial – jQuery and the Keyboard

jQuery is no doubt one of the greatest javascript resources you can get your hands one. One of the reasons for this is, without a doubt, its cross-browser compatibility which no doubt takes a lot of work to maintain. An area that this becomes more apparent is keyboard events, and more specifically, capturing such events. In this tutorial, we will be going through the basics of capturing keyboard events, which like most things in jQuery, is pretty simple.

Here is an example of what we will be putting together together today:

Please type in “SOTC”, notice most other characters are blocked.

So at the heart of mastering keyboard events in jQuery is the magical event.which property, which is passed to an key event handler function. For example:

$(‘#element’).keyup(function(eve) { alert(eve.which); });

This would alert the key code for the button being pressed, no matter what browser you are in, which is not an easy task by any means. What the good fellas over at jQuery have done for us is merge the different ways your browser determines what the key code is, and given us the event.which to use. This makes things so much easier, and much simpler.

So, to start our simple example, we need some very simple HTML:

<div>Please type in "SOTC", notice most other characters are blocked.</div>
<input id="test-input" type="text">

That’s all the html we will need. And in this quick example, our jQuery is very simple as well. To start with, let’s set a few variables, one of which grabs the character which was pressed when typing inside the textbox:

$(document).ready(function(){
       
  var str = "SOTC";
  $(‘#test-input’).keydown(function(eve){
   
     var charCount = $(this).val().length;
     var typedChar = String.fromCharCode(eve.which);
  });
});

So what we have here is a keydown event, which when fired sets two variables. One variable is the number of characters that has been entered in the textbox, and the other is the character that was pressed. We also have a variable that controls what the user has to type in (in this case, “SOTC”). All we have to do now is make sure the user types in the right characters, and to do this we just need a small if statement:

$(document).ready(function(){
       
  var str = "SOTC";
  $(‘#test-input’).keydown(function(eve){
   
     var charCount = $(this).val().length;
     var typedChar = String.fromCharCode(eve.which);
     
     /* If the key pressed is a letter and does not match the next
        character in the test string. */

     if(/\w/.test(typedChar) && typedChar != str.charAt(charCount))
     {
       /* Prevent the character from being added. */
       eve.preventDefault();
       return false;
     }
  });
});

Like the steps before it, this step is very small and simplistic. We have an if statement that makes sure the typedChar is a word character, and if it is, tests it against the next character in the test string. Now the regular expression in this test will still allow you to type in other characters such as “.” or “>”, but for the scope of this example, it is not that important.

What is important is that inside the if statement, we prevent the default action of the keypress, which in turn prevents the character from being added to the textbox. So, besides the loophole that allows special characters, you have to type in the right string…otherwise what you type will not even be added to the textbox. Essentially we force the user to type what we want.

So that is the basic idea behind jQuery and keyboard events. With event.which, you have a portal to capturing key presses for just about any browser. That wraps it up for this one, just remember that if you need coding help, all you have to do is Switch On The Code.

Leave a Reply

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