As discussed in yesterday’s blog post, it’s very very simple to wire up key events to your DOM objects such as form elements, or DIVs for example. In today’s post I’ll talk about taking it one step further by registering the key event, but also checking for, and acting upon specific key events, such as pressing TAB or ENTER.
The reason why we want to do this is simple – we want to cause a web application to do something on a specific key press. Luckily this is pretty easy with jQuery:
$(document).ready(function(){
$("#username").keyup(function(event){
if(event.keycode == 13)</p>
{ do_something(); }</p>
});
});
For every event there is an event object which we can interogate. The way we do this is we call the object property “keycode” which will return a numerical value pertaining to the key that was pressed. For example, above I am checking for keycode “13″, which is the numeric value for the [ENTER] key. There is a great resource on unixpapa which can help you out here for all other keycodes you may need.
Therefore, in the example above, the function do_something() will be called when the [ENTER] key is pressed and the focus is on the “#username” DOM object (assuming that its an input box for example).
These appear simplistic approaches – that’s because they are, yet most web applications don’t employ them.
Tomorrow I will be posting 10 awesome jQuery plugins which can increase form usability and therefore the success rate of submissions. A must for any serious application developer!
Similar Articles:
Using jQuery for great user feedback
Top 10 jQuery plugins for Form Usability
jQuery on Whitehouse.gov - A Closer look
Top 10 jQuery Image Plugins
jQuery - PHP & Ajax with the Twitter API












http://github.com/collin/keybinder/tree/master
Wire up your key presses in style.
Muy bueno el ejemplo
There’s a typo, should be “event.keyCode” and also for key events like “Tab” it should also be “keydown”
it’s keyCode