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.
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.18.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.
<script> // 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. }); </script>
For more information on creating YUI instances and on the
use()
method, see the
documentation for the YUI Global Object.
// 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.
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 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()
.
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!
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
If you've |
event |
A rollup of all modules below except
|
event-delegate &
node-event-delegate |
Adds the Y.delegate(...) and node.delegate(...) methods,
respectively, for event delegation
convenience.
|
event-simulate &
node-event-simulate |
Adds 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:
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 Currently, this event can only be subscribed with
|
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
This event can only be subscribed with
|
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. |
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.
Here is a sampling of some of the other ways to manage event subscriptions in YUI.
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.
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()
.
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.
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!");
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 |
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,
|
node.detachAll(); |
Works the same as |
node.purge(); // OR node.purge(true); // OR node.purge(true, 'click'); |
With no arguments,
Passing |
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
With
The |
Y.Event.detach('click', callback, '#foo'); |
Same as |
Y.Event.purgeElement('#foo', true, 'click'); |
Same as |
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.
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.
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.
Y.on()
or Y.delegate()
instead of node.on()
and node.delegate()
?after()
method. How does that work for DOM events?this
is the NodeList, not the individual Node. What's up with that?nodelist.delegate()
?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.
(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));
It depends what modules you've included. Check out the whitelisted events table.
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.
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')
.
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.
this
in
the callback will be the individual Node, not a
NodeList wrapping all matched elements.
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.
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.
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'); });
Details about domready
, available
, and contentready
events provided in
the event core. Read more...
What is event delegation and why you should be using it. A lot. Read more...
How to simulate user events like "click" or "keypress", what events can be simulated, and some important caveats. Read more...
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...
Details on the supported touch events, the touch/mouse abstraction layer events, and gesture based events like "flick". Read more...
focus
and blur
Events
Using the event-focus
module to simulate support for bubbling focus
and
blur
events.
Read more...
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...
Using the key
event to respond to specific users pressing specific keys or
or key combinations.
Read more...
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...
<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...
contextmenu
Events
Repairing cross browser keyboard support for the contextmenu
event.
Read more...
tap
Event
Using the event-tap
module for fast-click on touch devices.
Read more...
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 |
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 });
e.preventDefault()
click
or form submission and
page reload from a <form> submit
.
e.stopPropagation()
e.stopImmediatePropagation()
e.halt( [immediate=false] )
e.preventDefault(); e.stopPropagation();
or
e.preventDefault(); e.stopImmediatePropagation();
, depending on
the immediate parameter.
e.type
e.target
e.currentTarget
this
is the NodeList...).
e.relatedTarget
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.
e.keyCode
keypress
event or
any key in keydown
or keyup
. See event.keyCode
on MDC.
e.charCode
e.shiftKey
true
if the shift key was depressed during a key event.
e.ctrlKey
true
if the control key was depressed during a key event.
e.altKey
true
if the alt/option key was depressed during a key event.
e.metaKey
true
if the "Windows" key on PCs or command key on Macs was
depressed during a key event.
e.button
mouseup
events (NOT click
events), indicates
which mouse button is pressed.1
= left click, 2
= middle click, 3
= right click.
e.which
e.pageX
e.pageY
e.clientX
e.clientY
e.wheelDelta
]mousewheel
or DOMMouseScroll
events, the pixel distance of
the scroll.
e.touches
]
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
.
e.targetTouches
]
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.
e.changedTouches
]
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.
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 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.