Tuesday, January 25, 2011

Key Events

Keyboard events can sometimes trip up even seasoned developers. 

I'm listing the keyboard events below in order that they fire:

1. Keydown - fires 1st when a finger pushes down on a key

    a. You can prevent any input from displaying in the textbox or textarea.
    b. This is the event that fires when a key is held down.
    *   Use this event to prevent users from inputting numbers where text is expected or ensuring that the input is always in the correct format.
    ** You can detect the keycodes and map them or you can just translate them to charCodes and use a Regex to determine input validation.

2. Keypress - fires 2nd when a finger keeps a key down.

    a. At this point its too late to prevent the character from showing, but you can still remove it after it has      displayed.
    * If you check a character and then remove it after determining it is bad, the user will see a visible flash where the character shows up and then disappears, which is probably not the desired effect.

3. Keyup - fires 3rd when a finger pushes release a key

    a. Really just a point in time at which you can say all the input has completed and the decisions to show or not show the characters have already been made. 
    b. You can trim or remove or reformat at this point also.
    * Remember that this event fires before a "change" event, because the "change" events requires "blur" or clicking/tabbing off the textbox. (This also applies to the "blur" event of course.)

KeyDown vs OnKeyDown

Sometimes it can be confusing whether you should bind the events to "keydown" or "onkeydown".  The recommendation is to use jQuery's browser-agnostic "keydown" event to do the binding.  It will figure out the correct event name for the browser currently running. 

*This of course applies to keypress and keyup as well as most of the other bindable events.

You should always use jQuery's event.which.  This will normalize the input for all browsers so that you don't have to check event.which and event.charCode and event.keyCode.

No comments:

Post a Comment