Wednesday 26 June 2013

How To Attach Events To HTML Elements Created Dynamically

In one of my recent applications I had to use a jQuery plugin which need to run when the HTML <li> elements are ready. This plugin creates fancy tool tips for HTML elements having title attribute.
 
The <li> elements were created and appended dynamically to document body, by javascript. So I found that the plugin is not recognizing the title attributes of the li elements.

I made use of document.ready, li.ready etc. to run the plugin, but non of them worked for me.
 
So after making a good search I found one jQuery event handler called live(). This method can help in attaching events to any HTML element, whether it is created dynamically or not.

So if you are setting any event to any element/ selector, then it is automatically attached to that particular selector/element in future also, if they are created dynamically.
Syntax:

.live( events, handler(eventObject) )

Example: $("li").live("onmouseover",function(){
   //do your stuffs
});

This has different versions per different plugins.

$(selector).live(events, data, handler);                // jQuery 1.3+
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(document).on(events, selector, data, handler);        // jQuery 1.7+


Thanks,

No comments:

Post a Comment