Jump to Table of Contents


The YUI Event Utility provides APIs for working with the browser's DOM event system. It simplifies tasks like subscribing to button clicks or canceling <form> submits to, for example, allow sending data to the server via ajax.

In addition, the "Synthetic event" system supplies entirely new DOM events to subscribe to as well as fixing events that behave differently across browsers. Implementers can create their own DOM events triggered by specific user actions or other environmental criteria.

The API for working with DOM events is provided by the EventTarget class, which also services the Custom event infrastructure that is used throughout YUI. Read more about working with custom events in the EventTarget user guide.

Getting Started

To include the source files for Event and its dependencies, first load the YUI seed file if you haven't already loaded it.

<script src="http://yui.yahooapis.com/3.9.1/build/yui/yui-min.js"></script>

Next, create a new YUI instance for your application and populate it with the modules you need by specifying them as arguments to the YUI().use() method. YUI will automatically load any dependencies required by the modules you specify.

// Create a new YUI instance and populate it with the required modules.
YUI().use('event', function (Y) {
    // Event is available and ready for use. Add implementation
    // code here.

For more information on creating YUI instances and on the use() method, see the documentation for the YUI Global Object.

The Basics

Listening for events

// Step 1. Capture a button node
var button = Y.one("#readygo");

// Step 2. Subscribe to its click event with a callback function
button.on("click", function (e) {

    // Step 3. do stuff when the button is clicked


on(type, callback) is the main subscription method, and is available on every Node and NodeList.

Replace "click" with any other event name to subscribe to that event.

The Callback and the Event Object

button.on('click', function (e) {
    // `this` is the button Node, NOT the DOM element
    this.get('id'); // ==> 'readygo' (from <button id="readygo">...</button>)

    // Event properties that point to the DOM are also Node instances
    e.target.get('id'); // => 'readygo'

    // Stop the event's default behavior

    // Stop the event from bubbling up the DOM tree

Subscribed callbacks are passed a normalized event object as their first argument.

The keyword "this" in the callback will refer to the Node or NodeList that you subscribed from.

e.preventDefault() and e.stopPropagation()

Many events have a default behavior, such as the submit event serializing form data and making a new page request. Disable this behavior with e.preventDefault().

function setFilter(e) {
    // Stop the link from loading the href page

    // Now do my own thing instead
    var url = this.get('href').replace(/page/, 'partial');


    // `return false` is supported, but not preferred. use e.preventDefault()
    return false;

Y.one('#table-filter-link').on('click', setFilter);

Most events can be listened for on the specific element that originates them or from any of their parent elements, all the way up to the document. Prevent dispatching the event to subscriptions bound to elements further up the DOM tree with e.stopPropagation(). In practice, this is rarely useful.

Returning false from a callback will also stop the propagation of the event, which may cause unintended side effects.

e.stopPropagation() won't prevent the execution of other subscribers listening to the same element, only elements further up the DOM tree. If you need to stop all execution, use e.stopImmediatePropagation() or e.halt(true). The latter will also call e.preventDefault().

Detaching subscriptions

node.on() and all other subscription methods return a subscription object that can be used to unbind that subscription. Node also supports a detach() method and other ways to cleanup subscriptions.

// on() returns a subscription handle...
var sub = button.on("click", handleClick);

// ...that can be used to unbind the subscription

// Alternately, use the Node's detach() method
button.detach("click", handleClick);

Just this should take care of most of the simple event bindings you'll need. There's a lot more you can do, though, so read on!

What to use()

Before we get into more API goodies, let's talk about the Event Utility's module breakdown.

For starters, in most cases you probably won't use('event'). The core DOM event system ("event-base") is required by the "node-base" module, which itself if required by just about everything in YUI. So you probably already have the DOM event API and didn't know it!

Here is the full breakdown of modules in the DOM event system:

use("______", ...) What's in it?

The core DOM event subscription system as well as the DOM lifecycle events domready, contentready, and available. Notably, it does NOT include

  • event delegation
  • event simulation
  • synthetic events

If you've use()d anything, you probably have this already.

event A rollup of all modules below except
  • "event-simulate"
  • "node-event-simulate"
  • "node-event-delegate" (which is in the "node" rollup)
event-delegate &
Adds the Y.delegate(...) and node.delegate(...) methods, respectively, for event delegation convenience.
event-simulate &

Adds Y.Event.simulate(...) and node.simulate(...) for triggering native DOM events for unit testing.

Note: Faking DOM events should not be used in user facing code.


Supplies the infrastructure for creating new DOM events, "fixing" existing events with undesirable or inconsistent behavior, and all sorts of other things.

All of the modules below are synthetics.

event-flick Adds a "flick" event for touch or mouse interaction.
event-focus Fixes focus and blur events to bubble (for delegation).

The gestures rollup provides gesture events such as "flick" and "gesturemove", which normalize user interactions across touch and mouse or pointer based input devices. It contains the following modules:

  • "event-touch"
  • "event-move"
  • "event-flick"

In the future, may contain more gesture abstraction modules.

event-hover Adds a "hover" event which binds to two callbacks, one for the start, and one for the end of a mouse hover.
event-key Adds a "key" event which listens for specific, implementer defined, keys being pressed by the user.
event-mouseenter Adds "mouseenter" and "mouseleave" events. You probably want to use these instead of "mouseover" and "mouseout".

Adds a "mousewheel" event for monitoring users scrolling the window with the mousewheel. Event facades passed to the callback will have an e.wheelDelta property corresponding to the amount of scrolling.

Currently, this event can only be subscribed with Y.on("mousewheel", callback);

event-move Adds "gesturemovestart", "gesturemove", and "gesturemoveend" events that serve as abstractions over mouse and touch events, forking internally based on the client device.
event-outside Adds a "clickoutside" and several other outside events to trigger behavior based on actions taken outside a specific element.

Adds a "windowresize" event that only fires after a user has stopped dragging a window's resize handle. This normalizes the window.onresize event across browsers.

This event can only be subscribed with Y.on("windowresize", callback);

event-touch Adds support for subscribing to native touch and gesture events.
event-valuechange Adds a "valuechange" event that fires when input element text changes (this is harder than you think).
event-contextmenu Fixes bugs and inconstancies that can occur when the "contextmenu" event is fired via the keyboard. Adds sugar for working with the "contextmenu" event.
event-tap Adds a synthetic "tap" event that allows for fast-click on touch devices, while supporting mouse events as well.

Event Delegation

If you don't already know what event delegation is, you should read this quick overview. Short form: you need to be using this.

// single element subscription
node.on("click", handleClick);

// delegated subscription for all button clicks from inside the node
node.delegate("click", handleClick, "button, input[type=button]");

Creating a delegated subscription looks very much like creating any other event subscription with two differences. First, it's a different method name, delegate. Second, there is another argument: a CSS selector that is used to test the event's originating element to decide if the callback should be executed. If the event started at or inside an element matching the selector, the callback will execute.

Unlike node.on() subscriptions, the this object in node.delegate() callbacks will refer to the element that matched the css filter, not to node. We did this because likely your logic revolves around the nodes described by the filter, not around the element that contains them.

function handleClick (e) {
    // `this` is the button with class .remove, not the #items element
    // remove the containing LI

    // e.currentTarget is also the button.remove
    // e.container === Y.one('#items')

Y.one('#items').delegate('click', handleClick, 'button.remove');

For more complex target filtering, a function can be passed instead of a css selector. See the API docs for more details.

As noted above, the event-delegate module is included in the event rollup, but node-event-delegate isn't. We recommend using delegation from the Node API, so you should use() either node-event-delegate or the node rollup.

More Event API Goodness

Here is a sampling of some of the other ways to manage event subscriptions in YUI.

Subscribe from Y

// Y.on() takes a third argument which is the Node, DOM element,
// or CSS selector of the element(s) to bind
Y.on("click", handleClick, "#readygo");

// Y.delegate() similarly takes the containing element or selector
// as the third argument
Y.delegate("click", handleClick, "#container", "button, input[type=button]");

An alternate syntax for DOM subscriptions is using Y.on() or Y.delegate(). When identifying the target by a CSS selector, these methods can be used regardless if the element is currently available for scripting. If it's not yet on the page, a poll will regularly look for it (for a few seconds) and the subscription will be automatically attached when the element is found. Relying on this behavior can introduce race conditions, though, so use it wisely.

Use of Y.on() instead of node.on() is largely a stylistic preference, though there are some technical differences.

One time subscriptions

tabLabel.once('mouseover', loadTabContent);

If you only want to execute a callback on the first occurrence of an event, use node.once() or Y.once(). The subscription will automatically be detached after the event fires.

The signature for once() is the same as on().

Grouping subscriptions

Pass an object to subscribe to multiple events, each with their own callback

function validate(e) { ... }
function clearPlaceholder(e) { ... }

var groupSub = inputNode.on({
    blur    : validate,
    keypress: validate,
    focus   : clearPlaceholder

// Detach the blur, keypress, and focus subscriptions in one call

Pass an array to subscribe to multiple events with the same callback

function activate(e) { ... }

groupSub = inputNode.on(['focus', 'mouseover'], activate);

// Detach the focus and mouseover subscriptions

Prefix the event name with a category to allow detaching multiple subscriptions by that category.

inputNode.on('my-category|focus', activate);
inputNode.on('my-category|mouseover', activate);

// You can detach specific subscriptions by 'my-category|focus' or all with |*

The once() and delegate() methods also support these alternate signatures.

Binding this and additional callback arguments

By default, the "this" object in subscription callbacks will be the Node or NodeList that subscribed to them. Override this default by passing your own this object as the third argument to on() or the fourth to delegate(). Note that the argument index is shifted when using Y.on() and Y.delegate() or synthetic events with custom signatures.

// equivalent to node.on('click', function (e) { overlay.hide(e); });
node.on('click', overlay.show, overlay);

node.once('mouseover', door.unlock, door);

// `this` override comes after the filter; also shifted for the 'key' event's
// custom signature.
container.delegate('key', validator.isValid, 'enter,tab', 'input', validator);

// Corresponding alternatives from Y
Y.on('click', overlay.show, '#show', overlay);

Y.once('mouseover', door.unlock, '#gate13', door);

Y.delegate('key', validator.isValid, '#myForm', 'enter,tab', 'input', validator);

Additional arguments passed to the subscription methods will be sent along to the callback after the event facade. If you want to bind extra arguments, but don't want to override the "this" object, pass null for the this argument.

MyClass.prototype = {
    someMethod: function (param) {
        Y.log(param); // => "I'm Extra!"

    handleClick: function (e, extraParam) {

var instance = new Y.MyClass();

// The extra arg is passed as the second param to the callback after `e`
Y.one('#readygo').on('click', instance.handleClick, instance, "I'm Extra!");

More ways to clean up subscriptions

There are a lot of options for detaching events in YUI. See the table below for details.

Method What it does
var subscription = node.on('click', callback);


Removes a specific subscription or, if created with one of the group subscription methods, a group of subscriptions.

Generally, this is the best method to use.

node.on('foo-category|click', callback);

// OR

Removes a subscription or group of subscriptions that included the specified category in the subscription event type.

This is typically only safe in implementation code, not module code, because multiple subscriptions using the same type and category will be detached by the call to detach.

node.detach('click', callback);
// OR
// OR

If you have a reference to the subscribed callback function, (but not a subscription handle) use the two argument signature.

With one argument, detach will remove all subscriptions for the specified event. With no arguments, it removes all subscriptions for all events.

detach does not remove subscriptions from descendant nodes.


Works the same as node.detach().

// OR
// OR
node.purge(true, 'click');

With no arguments, purge works the same as node.detach().

Passing true as a first argument will remove all subscriptions for all events from the node and its descendant subtree. Passing an event type as a second argument will only deep purge subscriptions to that event.


Removes subscriptions for all events only from the descendants of a node after removing them from the DOM.

// OR

With no arguments, works like node.detach().

With true as a first argument, it works like node.purge(true).

The destroy method does more than detaching event subscribers. Read the API docs for details.

Y.Event.detach('click', callback, '#foo');

Same as Y.one('#foo').detach( [other args] ).

Y.Event.purgeElement('#foo', true, 'click');

Same as Y.one('#foo').purge( [other args] ).

Simulate browser events

For creating automated functional tests, being able to simulate user interaction can be crucial. That's where the node-event-simulate module comes in.

YUI().use('test', 'node-event-simulate', 'fancy', function (Y) {

var test = new Y.Test.Case({

    "clicking close button should dismiss UI": function () {

        var widget      = new Y.MyFancyWidget().render('#here'),
            uiBox       = widget.get('boundingBox'),
            closeButton = uiBox.one('.close-button');


        Y.Assert.isFalse( uiBox.inDoc() );

node.simulate( type, eventProperties ) creates a native DOM event that will bubble (if appropriate), but will not trigger native default behavior. For example, node.simulate('submit') will not send data to the server for a page reload.

Read more about event simulation here.

Synthetic Events

The event system supports adding new abstractions over the native DOM environment that behave like DOM events. These abstractions are called synthetic events, and you can subscribe to them like any other DOM event with node.on() or node.delegate().

Y.one('#dialog').on('clickoutside', function (e) {

Y.one('#editable-table').delegate('key', saveAndAdvance, 'tab', 'input');

The synthetic events that are available as core YUI modules are listed in the table of modules above, though there are others in the Gallery. Most events listed in the table are linked to pages that describe the specific event in more detail.

Creating DOM events

Create your own synthetic events with Y.Event.define(type, config).

Y.Event.define("tripleclick", {

    // The setup logic executed when node.on('tripleclick', callback) is called
    on: function (node, subscription, notifier) {
        // supporting methods can be referenced from `this`

        // To make detaching easy, a common pattern is to add the subscription
        // for the supporting DOM event to the subscription object passed in.
        // This is then referenced in the detach() method below.
        subscription._handle = node.on('click', function (e) {
            if (subscription._timer) {

            if (++subscription._counter === 3) {

                // The notifier triggers the subscriptions to be executed.
                // Pass its fire() method the triggering DOM event facade
            } else {
                subscription._timer =
                    Y.later(300, this, this._clear, [subscription]);

    // The logic executed when the 'tripleclick' subscription is `detach()`ed
    detach: function (node, subscription, notifier) {
        // Clean up supporting DOM subscriptions and other external hooks
        // when the synthetic event subscription is detached.

        if (subscription._timer) {

    // Additional methods can be added to support the lifecycle methods
    _clear: function (subscription) {
        subscription._counter = 0;
        subscription._timer = null;


After the synthetic event is defined, it is available for every Node and NodeList to subscribe to.

Y.one('#hellokitty').on('tripleclick', omgYayCantClickEnough);

There is additional configuration to add support for delegate() or extra subscription arguments, but often very little extra code is needed.


My callback is executing at the wrong time. What's going on?

It's likely that you've included parenthesis in the subscription.

node.on('click', someFunction());
node.on('click', myObject.someFunction());

node.on('click', someFunction);
node.on('click', myObject.someFunction, myObject);

Including the parens makes the function execute immediately, and pass the return value from the function to node.on('click', [RETURN VALUE]). To pass a function around, just omit the parens.

I'm getting an error in my callback that "(some object) has no method (someMethodOnMyObject)". What am I missing?

You may be passing an object method to on(), but forgot to include the this object override parameter in the subscription.

Another option to make sure object methods are called with the correct this object is to use `Y.bind(obj.method, obj)` or `Y.rbind(obj.method, obj)`.

node.on('click', myObj.method);

node.on('click', myObj.method, myObj);

// RIGHT (alternate)
node.on('click', Y.rbind(obj.method, obj));

What events can I subscribe to?

It depends what modules you've included. Check out the whitelisted events table.

Why isn't on() chainable?

After much deliberation, the YUI team decided that returning a subscription handle was preferable to chaining in order to better support clean event detaching across the various scenarios that DOM and custom events are used.

In any sizable application, managing event subscriptions becomes increasingly important, and detaching events must be done with precision. Because YUI allows duplicate subscriptions, any host-based detach method will necessarily be less than 100% reliable with respect to avoiding removal of subscriptions made by other parts of the system.

Otherwise, it's common to subscribe to events with anonymous functions, which makes it impossible to detach the specific subscription by signature because you don't have a function reference to use to identify the specific subscription to remove. Subscription categories can be used, but are also less precise than dealing with a specific subscription object.

Why would I use Y.on() or Y.delegate() instead of node.on() and node.delegate()?

It's largely a stylistic preference, but there are some technical differences when passing a selector string as a the third argument to Y.on() or Y.delegate() (ala Y.on('click', callback, '#some select.or-string').

  1. Y.on() uses the Selector engine directly rather than calling through Y.all(...).

    The benefit here is that the Node and NodeList constructors add the slightest bit of overhead to the subscription process.

  2. When passing a selector that matches multiple elements, the this in the callback will be the individual Node, not a NodeList wrapping all matched elements.
  3. If called before the elements matching the selector are attached to the DOM, it will poll for a few seconds and automatically attach the subscription when the first matching element is found.

    Note, if using a selector that matches multiple elements, the poll will attach the subscription the first time Selector finds a match. This may not include all the elements because either the DOM is not fully updated yet, or the code that adds the matching elements may happen in batches.

    In practice, it is best to avoid reliance on this behavior.

EventTarget also provides an after() method. How does that work for DOM events?

node.after(...) is equivalent to node.on(...). The DOM doesn't expose an "after" moment to hook into.

When I subscribe to an event from a NodeList, this is the NodeList, not the individual Node. What's up with that?

In the callback, e.currentTarget will always refer to the individual Node. However, if you call

Y.all('#some select.or-string').on('click', function (e) {
    // how do I reference the NodeList?

you can't reference the NodeList captured by Y.all() without calling Y.all() again, but that results in unnecessary overhead, and may match different elements in the subsequent call.

In general, you should avoid nodelist.on() anyway, in favor of event delegation.

Where is nodelist.delegate()?

The point of delegation is to reduce the number of subscriptions being made. nodelist.delegate() would be philosophically at odds with that. Either call node.delegate() from an element higher up the DOM tree, or if you must delegate the same event and callback from multiple containers, use

nodelist.each(function (node) {
    node.delegate('click', callback, '.not-recommended');

More Reading

Page Lifecycle events

Details about domready, available, and contentready events provided in the event core. Read more...

Event Delegation

What is event delegation and why you should be using it. A lot. Read more...

Event Simulation

How to simulate user events like "click" or "keypress", what events can be simulated, and some important caveats. Read more...

Create New DOM Events

How to create a tailor made DOM event for subscription or delegation from any Node. This is a great way to encapsulate and label more comples user behaviors. Read more...

Working With Touch Events

Details on the supported touch events, the touch/mouse abstraction layer events, and gesture based events like "flick". Read more...

Delegating the focus and blur Events

Using the event-focus module to simulate support for bubbling focus and blur events. Read more...

The hover, mouseenter, and mouseleave Events

Describes why mouseenter and mouseleave events are usually what you want when you subscribe to mouseover and mouseout, and goes over using the hover event (which uses the other two under the hood). Read more...

Complex Keyboard Input Filtering

Using the key event to respond to specific users pressing specific keys or or key combinations. Read more...

Responding to Events outside of a Node

Details the host of "outside" events that can be used to trigger behavior when users interact with element outside of the relevant Node. Think closing popups if a user clicks somewhere else on the page. Read more...

Monitoring Changes to <input> and <textarea> Values

Using the valuechange event to catch the moments when a user types, cuts, pastes, or otherwise alters the value in an input field. No, input.on('change', callback) is not enough. Read more...

Keyboard Accessible contextmenu Events

Repairing cross browser keyboard support for the contextmenu event. Read more...

The tap Event

Using the event-tap module for fast-click on touch devices. Read more...

Appendix A: Whitelisted DOM events

Event Added by
abort node-base
beforeunload node-base
blur node-base
change node-base
click node-base
close node-base
command node-base
contextmenu node-base
dblclick node-base
DOMMouseScroll node-base
drag node-base
dragstart node-base
dragenter node-base
dragover node-base
dragleave node-base
dragend node-base
drop node-base
error node-base
focus node-base
key node-base
keydown node-base
keypress node-base
keyup node-base
load node-base
message node-base
mousedown node-base
mouseenter node-base
mouseleave node-base
mousemove node-base
mousemultiwheel node-base
mouseout node-base
mouseover node-base
mouseup node-base
mousewheel node-base
orientationchange node-base
reset node-base
resize node-base
select node-base
selectstart node-base
submit node-base
scroll node-base
tap event-tap
textInput node-base
unload node-base
DOMActivate node-event-html5
DOMContentLoaded node-event-html5
afterprint node-event-html5
beforeprint node-event-html5
canplay node-event-html5
canplaythrough node-event-html5
durationchange node-event-html5
emptied node-event-html5
ended node-event-html5
formchange node-event-html5
forminput node-event-html5
hashchange node-event-html5
input node-event-html5
invalid node-event-html5
loadedmetadata node-event-html5
loadeddata node-event-html5
loadstart node-event-html5
offline node-event-html5
online node-event-html5
pagehide node-event-html5
pageshow node-event-html5
pause node-event-html5
play node-event-html5
playing node-event-html5
popstate node-event-html5 or history
progress node-event-html5
ratechange node-event-html5
readystatechange node-event-html5
redo node-event-html5
seeking node-event-html5
seeked node-event-html5
show node-event-html5
stalled node-event-html5
suspend node-event-html5
timeupdate node-event-html5
undo node-event-html5
volumechange node-event-html5
waiting node-event-html5
touchstart event-touch
touchmove event-touch
touchend event-touch
touchcancel event-touch
gesturestart event-touch
gesturechange event-touch
gestureend event-touch
transitionend or webkitTransitionEnd transition

Adding to the DOM event whitelist

If you need to use an event that isn't included in this list, and not supplied by a synthetic event, you can expand the whitelist by adding the event names to the Y.Node.DOM_EVENTS object.

// Allow for subscription to some mostly cross-browser mutation events
Y.mix(Y.Node.DOM_EVENTS, {
    DOMNodeInserted: true,
    DOMNodeRemoved: true,
    DOMCharacterDataModified: true

Appendix B: EventFacade properties and methods


Prevents the default action associated with the event. E.g. page navigation from an <a>nchor click or form submission and page reload from a <form> submit.
Stops the event from bubbling further up the DOM tree. This does not prevent the default action if there is one. Subsequent event subscribers will be executed.
Stops the event from bubbling further up the DOM tree. This does not prevent the default action if there is one. Subsequent event subscribers will NOT be executed.
e.halt( [immediate=false] )
Alias for e.preventDefault(); e.stopPropagation(); or e.preventDefault(); e.stopImmediatePropagation();, depending on the immediate parameter.


The name of the event. E.g. "click", "keyup", or "load".
The Node instance that originated the event (see the description of event delegation for reference)
The Node instance that subscribed to the event. In the case of subscriptions from NodeLists, this is still the individual Node instance (see When I subscribe to an event from a NodeList, this is the NodeList...).
For mouseover events, this will be the Node instance of where the mouse travelled from. For mouseout, it will be the Node that the mouse travelled to.

Keyboard event properties

The unicode value of a non-character key in a keypress event or any key in keydown or keyup. See event.keyCode on MDC.
The Unicode value of a character key pressed during a keypress event. See event.charCode on MDC.
true if the shift key was depressed during a key event.
true if the control key was depressed during a key event.
true if the alt/option key was depressed during a key event.
true if the "Windows" key on PCs or command key on Macs was depressed during a key event.

Mouse event properties

For mouseup events (NOT click events), indicates which mouse button is pressed.
1 = left click, 2 = middle click, 3 = right click.
Alias for e.button.
The horizontal coordinate of the event relative to whole document.
The vertical coordinate of the event relative to whole document.
The horizontal coordinate of the event relative to viewport, regardless of scrolling.
The vertical coordinate of the event relative to viewport, regardless of scrolling.
For mousewheel or DOMMouseScroll events, the pixel distance of the scroll.

Touch event properties


An array of Touch objects, where each Touch object represents a finger currently touching the surface (regardless of the target of the current event). For example, if you have two fingers on the surface, this array would have two Touch objects, one for each finger.

The common set of properties currently on a Touch object, which can be relied up across environments, are target, clientX, clientY, pageX, pageY, screenX, screenY and identifier.


An array of Touch objects for every point of contact that is touching the surface, and started on the element that is the target of the current event.


An array of Touch objects representing all touches that changed in this event.

This property is most useful in touchEnd events, to identify the set of touches which were removed from the surface, which resulted in the firing of the event.

Gesture event properties (currently iOS specific)

These properties are unique to Webkit on iOS currently, and are provided on the event facade when listening for the iOS gesturestart, gesturechange and gestureend multi-touch events.

See Apple's documentation for scale.
See Apple's documentation for rotation.

See the W3C Touch Events Specification, derived from the Webkit model, for more details.

Synthetic events may add or modify event facade properties. These should be included in the documentation for the specific synthetic event.

For more details, check out the MDC documentation.