YUI3: Controlling key strokes events (keyup, keydown, keypress)

In this post I want to cover the general specifications related with keystrokes in YUI3. Basically you will see few examples and a bunch of links to the YUI Library official documentation.

There are two different ways to define a keylistener in YUI3:

Considering that in YUI3 most of the DOM references are YUI Node objects, using the ‘on’ method for a node object is the most reasonable approach for all kind of listeners, including keylistener.

keylistener in YUI3

We can use ‘keydown’ or ‘keyup’ to be more specific in the definition.

Also, we can use the traditional way:

keylistener in YUI3 traditional way

or we can use the event name ‘key’ and using the 4th argument to be more specific in the event definition, check this example:

keylistener in YUI3 example

We can also use [press] or [up], or we can be even more specific describing which key combination we want to listen for, like this combination: [press:65,66+shift+ctrl], this event definition will fire only if keyCode 65 or 66 is detected during a keypress event while shift and control are held down.

Check this advanced example:

keylistener in YUI3 edvanced example

In this example, we have a definition for keydown for keyCodes 65, 12 or 13, plus the shift key held down at the same time. The 5th argument represents the execution context (Y), and the rest of the arguments will be passed thru the handler method.

Of course, we can add this kind of event to any DOM element/tag, but it only makes sense if the event can get the focus, usually all kind of form input fields, anchors, images, buttons, etc.

Controlling the event propagation and the default behavior:

YUI3 controls all the events in the same way, wrapping the event object (variable ‘e’ passed thru the handler function) into a more consistent object. This feature allows us to control the object propagation easily. We can use preventDefault and stopPropagation directly, instead of invoking YAHOO.util.Event.stopPropagation or YAHOO.util.Event.preventDefault as we used to do in YUI2.x. Here is a very simple example:

keylistener in YUI3 simple example

Global keystroke events:

We can also listen for global events. Defining a listener for an especial element called ‘document‘, we will receive a notification for every keystroke.

notification for every keystroke

Simulating keystroke events:

Another feature, and this one is new in YUI3, is the event simulation, which means you can simulate user actions like clicks and keystrokes. I hope you don’t need to use it, because I really think that with a good design you don’t need to use this feature other than in a js unit test, but just in case, here is an example:

Simulating keystroke events