jQuery: Acting on specific key events

Just Posted: Apple Likely to Give Education Rather than Resolution for iPhone 4 Antenna Issues

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!

Some books to help you learn:

Learning jQuery

Learning jQuery

JQuery In Action

JQuery In Action

jQuery Reference Guide

jQuery Reference Guide

7 Responses to “jQuery: Acting on specific key events”

  1. collin says:

    http://github.com/collin/keybinder/tree/master

    Wire up your key presses in style.

  2. Diego says:

    Muy bueno el ejemplo

  3. Matt says:

    There’s a typo, should be “event.keyCode” and also for key events like “Tab” it should also be “keydown”

  4. T says:

    it’s keyCode

Trackbacks/Pingbacks

  1. [...] to this post on doing similar things in jquery for pointing me in the right [...]

  2. My Domain says:

    Joe…

    Check out my domain sometime….

Leave a Reply