The YUI Event Utility provides APIs for working with the browser's DOM event system. It simplifies tasks like subscribing to button `click`s or canceling <form> `submit`s 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}}

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 ) // Event properties that point to the DOM are also Node instances e.target.get('id'); // => 'readygo' // Stop the event's default behavior e.preventDefault(); // Stop the event from bubbling up the DOM tree e.stopPropagation(); }); ```

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 e.preventDefault(); // Now do my own thing instead var url = this.get('href').replace(/page/, 'partial'); Y.one('#contentArea').load(url); // `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 sub.detach(); // 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?
`event-base`

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` &
`node-event-delegate`
Adds the `Y.delegate(...)` and `node.delegate(...)` methods, respectively, for event delegation convenience.
`event-simulate` &
`node-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.

`event-synthetic`

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).
`event-gestures`

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".
`event-mousewheel`

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.
`event-resize`

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 this.ancestor('li').remove(); // 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 groupSub.detach(); ```

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 groupSub.detach(); ```

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 |* inputNode.detach('my-category|*'); ```

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) { this.someMethod(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); subscription.detach(); ```

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); node.detach('foo-category|click'); // OR node.detach('foo-category|*'); ```

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 node.detach('click'); // OR node.detach(): ```

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.

``` node.detachAll(); ```

Works the same as `node.detach()`.

``` node.purge(); // OR node.purge(true); // 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.

``` node.empty(); ```

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

``` node.destroy(); // OR node.destroy(true); ```

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'); closeButton.simulate('click'); 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) { this.transition('fadeOut'); }); 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` this._clear(subscription); // 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) { subscription._timer.cancel(); } if (++subscription._counter === 3) { this._clear(subscription); // The notifier triggers the subscriptions to be executed. // Pass its fire() method the triggering DOM event facade notifier.fire(e); } 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. subscription._handle.detach(); if (subscription._timer) { subscription._timer.cancel(); } }, // 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.

Troubleshooting/FAQ

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

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

``` // WRONG node.on('click', someFunction()); node.on('click', myObject.someFunction()); // RIGHT 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)`.

``` // WRONG node.on('click', myObj.method); // RIGHT 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 `` and `