JavaScript - - By Sam Deering

jQuery Binding to Created Elements

To clear a few things up about adding events to elements that are injected dynamically into the DOM (ie – they don’t exist when the page is loaded).

Best Practice Methods

  • Use .Bind() and .Live() instead of .Click().
  • Use .Bind() for static DOM elements (elements that are loaded with the page).
  • Use .Live() for dynamic DOM elements (elements changed/inserted via JavaScript).


In this example it is an ordered list which appears once you have loaded a JSON file into the tool. Then a mouse hover event has been applied to every component in the DOM.

/*mouse IN hover to show path of node*/
$('#div li').live('mouseenter', function () {
    //do something

/*click event for hyperlink*/
$('#div a').bind('click', function (e) {
	//don't follow the hyperlink href
    //do something else

Online Demo

Other Live Options

There is a live query plugin which can handle these for you with just one declaration. LIVE QUERY PLUGIN: I’ll write more about the live query plugin when i get the chance to check it out properly and test it.

Also see: Binding to elements with the same id