Thursday, May 20, 2010

JQuery HowTo: How to bind events to AJAX loaded elements

We all use jQuery's AJAX helpers like $.get(), $.post() and $.load(). We also all use jQuery's event bindings. When you use them both, problems such as your event bindings like click() are not bided to your new AJAX loaded elements. To solve this problem you need to bind events to your newly loaded elements.

NOTE:
Make sure you don't bind the same event to the elements with this event already bound.

TIP:
You should somehow separate newly created elements and then bind event in callback of an AJAX function.

Regarding the tip above. Here are two ways of separating AJAX loaded content:

  1. You can load into some specific container <div id="ajax-loaded"></div> and then apply your events to the elements inside this container (Ex: $('#ajax-loaded .my-button').click(...)).
  2. Add some class to your elements that are loaded on the server side.

You might also be interested in:

Update: Added a demo page that shows how to bind events to AJAX loaded elements here.

No comments: