Learn YUI3: Attach Event to Dynamic Content

How would you attach event to dynamically generated content such as li, div? Many elements are dynamically created based on user action. Something like search result, carousel, or other kind of tool where you have next, prev button generally add content dynamically to the container.

Usually one may thing of adding a time based JavaScript function setTimeout/setInterval etc in loop to check for such dynamically generated elements. Or one may think of calling a function from where these dynamic elements/dynamic contents are getting created. But this method is expensive in the context we are talking. For a 1000 div, li etc we need to attach events to 1000 elements each time new content comes and also we need to loop through to check for the new content.

For the situation where content are created dynamically, delegate method work wonderfully.

YUI3 has delegate method and JQuery has .on() and delegate() and live() (older version) method. For reading more on the benefits of delegate method compared to directly assigning the event in the said context, read here.

Suppose here is our sample code:

<ul class="container">

Suppose above li can change dynamically. We will add event handler to UL with class=container. With this whenever new li comes to this UL, that will still be li and we
can work on the selector based on this.

YUI().use('node', function(Y) {
	Y.one('ul.container').delegate('click', myHandler, 'li');
	function myHandler(e) {

Delegate method is also available just like .on() is available. It can be called from YUI node instance. Just make sure either node or node-event-delegate is used in YUI.use().

Y.one('ul.container').delegate('click', myHandler, 'li');

Once I worked on hover event for image inside li.

YUI().use('event-delegate', 'node-event-delegate', 'event-hover', function(Y) {
	var container = Y.one('ul.container');
	container.delegate("hover", onHover, endHover, 'li img');
	function onHover() {}
	function endHover() {}

I have not tested any of the above code but this is how it works. I showed the way it works and when we should think of delegation and performance issue attached with it. Use the reference material for greater details. Enjoy this working online demo of YUI3 event delegation as well.