YUI 3.x Home -

YUI Library Examples: Node: NodeList Events

Node: NodeList Events

This example demonstrates how to use events with NodeList instances.

Clicking a box will update its content.

  • i am lorem

  • i am ispum

Setting up the NodeList

First we need some HTML to work with.

  1. <ul id="demo">
  2. <li><p>i am <em>lorem</em></p></li>
  3. <li><p>i am <strong>ispum</strong></p></li>
  4. </ul>
<ul id="demo">
    <li><p>i am <em>lorem</em></p></li>
    <li><p>i am <strong>ispum</strong></p></li>
</ul>

Handling Events

Next we will add a handler to run when the event is fired. In our handler we will update the node with the type of the event.

Note that the event handler receives an event object with its currentTarget set to the current Node instance, and the actual node clicked as the target. The context of the handler is the NodeList instance, so this refers to our NodeList instance.

  1. var onClick = function(e) {
  2. e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
  3. this.addClass('yui-pass');
  4. };
    var onClick = function(e) {
        e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
        this.addClass('yui-pass');
    };

Attaching Events

We can assign our handler to all of the items by using the all method to get a NodeList instance and using the on method to subscribe to the event.

  1. Y.all('#demo li').on('click', onClick);
Y.all('#demo li').on('click', onClick);

Full Script Source

  1. YUI().use('node', function(Y) {
  2. var onClick = function(e) {
  3. e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
  4. this.addClass('yui-pass');
  5. };
  6.  
  7. Y.all('#demo li').on('click', onClick);
  8. });
YUI().use('node', function(Y) {
    var onClick = function(e) {
        e.currentTarget.setContent(e.type + ': ' + e.target.get('tagName'));
        this.addClass('yui-pass');
    };
 
    Y.all('#demo li').on('click', onClick);
});

Copyright © 2009 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings