JavaScript
Article

jQuery Binding to Created Elements

By Sam Deering

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).

Example

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
	e.preventDefault();
    //do something else
	myFunction();
});

Online Demo

Other Live Options

There is a live query plugin which can handle these for you with just one declaration. LIVE QUERY PLUGIN: http://brandonaaron.net/code/livequery/demos 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

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.