OnKeyEvents < Element

OnKey events occur when the keyboard is used when elements have focus. Some browsers may or may not fire events for some elements. Input elements and anchors are a safe choice because they can obtain focus. One technique to insure a key event gets caught is to place focus on an anchor that’s shown off screen and handling key events on that anchor.

Key event order

Key events are handled in this order: OnKeyDown, OnKeyPress then OnKeyUp. OnKeyPress handles slightly differently than the other two events, but the KeyEventArgs passed to the handler is the same for all three events so handling them can occur the same way. OnKeyPress is typically not fired on most browser for non character producing keys. However, some browsers will produce a character for some keys such as Backspace, Home, PageUp, etc. Because of this, OnKeyPress will fire, but the Character field will be null as non-visible characters are caught and are made sure not to be passed to your handler.

One final note, OnKeyDown will fire before any text is added, where as OnKeyUp will fire after text has been added. So checking for a text value of an input field will fail if you check for it in OnKeyDown.

KeyEventArgs in depth

The KeyEventArgs passed to a handler contains quite a bit of information about a key event. The Character property contains the character that was produced from the key event, where as the Key property contains a KeyCode value for the key pressed. For example: if Capslock is on, hitting the A key will cause the Character field to be “A” and the Key to equal Keys.A.  Without Capslock, the Character will be “a”.

There is a Keys enumeration that can be used to easily check what Key is being pressed. Below is an example:

var validCharacters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];

function handleKey(e){
   e.Handled = !validCharacters.Contains(e.Character);


This simple handler will suppress anything put into the textbox that’s not a number. It checks the Character against a set of valid keys. If the key is invalid, Handled is set to true, which suppresses default execution of a key press, which is to add the text to the textbox.


Finally, the Modifiers field contains a set of flags for what modifiers are being held down. These are Modifiers.ShiftKey, Modifiers.AltKey and Modifiers.ControlKey. To check for CapsLock, use Keyboard.CapsLock. Here is an example of checking them:


function noUpper(e){
    e.Handled = e.Modifiers && Modifiers.Shift ^ Keyboard.CapsLock;
    // Can't use upper case characters! By the way ^ is XOR. Look it up!

Last edited Mar 26, 2011 at 7:11 PM by dahrkdaiz, version 3


No comments yet.