This example demonstrates using a single event listener on a list to delegate clicks on the list items.
- Click me if you don't mind...
- Click me if you don't mind...
- Click me if you don't mind...
- Click me if you don't mind...
Setting up the HTML
First we need some HTML to work with.
<ul id="demo"> <li>Click me if you don't mind...</li> <li>Click me if you don't mind...</li> <li>Click me if you don't mind...</li> <li>Click me if you don't mind...</li> </ul>
Geting a NodeList Instance
We will use the all
method of our YUI instance to get a NodeList
instance to work with.
var nodes = Y.all('#demo li');
Delegating Node Events
In this example, we will listen for a click
event on the list and handle it at the item level and use information from the event
object to update the nodes.
var onClick = function(e) { e.currentTarget.addClass('highlight'); // e.currentTarget === #demo li e.target.setHTML('Thanks for the click!'); // e.target === #demo li or #demo li em e.container.setStyle('border', '5px solid #FFA100'); // e.container === #demo nodes.filter(':not(.highlight)').setHTML('What about me?'); };
Now we just assign the handler to the UL
using the delegate
method to handle clicks on each LI
.
Y.one('#demo').delegate('click', onClick, 'li');
Complete Example Source
<style> #demo li { height: 3em; } </style> <ul id="demo"> <li><em>Click me if you don't mind...</em></li> <li><em>Click me if you don't mind...</em></li> <li><em>Click me if you don't mind...</em></li> <li><em>Click me if you don't mind...</em></li> </ul> <script type="text/javascript"> YUI().use('node', function(Y) { var nodes = Y.all('#demo li'); var onClick = function(e) { e.currentTarget.addClass('highlight'); // e.currentTarget === #demo li e.target.setHTML('Thanks for the click!'); // e.target === #demo li or #demo li em e.container.setStyle('border', '5px solid #FFA100'); // e.container === #demo nodes.filter(':not(.highlight)').setHTML('What about me?'); }; Y.one('#demo').delegate('click', onClick, 'li'); }); </script>