Mini-Tut: Using jQuery .live() With Dynamic Content

Mini-Tut: Using jQuery .live() With Dynamic Content
March 13, 20100 Comments

When using jQuery and loading content dynamically or with an AJAX call, any event attached to the content that is loaded either has to be rebound again after the content has been loaded or you can attach an event handler using the .live() event.

Here is an example of rebinding an event after dynamic content has been loaded:


Now, that's all well and fine if you have only a few events to bind. If not, you have a lot of code to write to rebind every function after your dynamic content has loaded. Doesn't sound fun does it? You could do that, or you could use the .live() event.

The .live() event is a variation on the basic .bind() method for attaching event handlers to elements. The difference between .bind() and .live() is after loading dynamic content such as appending a div to another, our events won't work on that div once it's been appended, .bind() will do nothing.

$('.clickme').bind('click', function() {
  // Bound handler called.
});

Now if we add another element dynamically, the above event will do nothing.


$('body').append('<div class="clickme">Another element</div>');

But if we use the .live() method, our dynamic div can be referenced without having to rebind again and again for each event.

$('.clickme').live('click', function() {
  // Live handler called.
});

That's about as basic as you can get for referencing items in dynamically loaded content without having to write tons of code and rebinding each event every time. For more information on the .live() event visit the jQuery API Documentation.

Author: Jason

Hi, I'm Jason. A front end developer from Grand Rapids, Michigan, and founder of VagrantRadio. I enjoy working with Css, jQuery, Php, learning new techniques in Photoshop and you should follow me on Twitter or Snipplr.

Mojo Themes
Scroll to top