jquery binding events to dynamically loaded html elements

ahhishek picture ahhishek · Jun 19, 2011 · Viewed 29.9k times · Source

using jquery we can attach event handlers to the elements present in page, this is done inside document.ready() function. Now my difficulty is i have some elements like links etc loaded later (using ajax request) after document is downloaded . So those new elements are failing to bind with the handlers I defined in page. Is there any way to know when followed ajax queries are finish and then inside that i can bind my event handlers.

Thanks in advance

Answer

user113716 picture user113716 · Jun 19, 2011

The various ajax methods accept a callback where you can bind the handlers to the new elements.

You can also use event delegation with the delegate()[docs] method or the live()[docs] method.

The concept of event delegation is that you do not bind the handler to the element itself, but rather to some parent container that exists when the page loads.

The events bubble up from the elements inside the container, and when it reaches the container, a selector is run to see if the element that received the event should invoke the handler.

For example:

<div id="some_container"> <!-- this is present when the page loads -->

    <a class="link">some button</a>  <!-- this is present when the page loads -->
    <a class="link">some button</a>  <!-- this is present when the page loads -->
    <a class="link">some button</a>  <!-- this is present when the page loads -->


    <a class="link">some button</a>  <!-- this one is dynamic -->
    <a class="link">some button</a>  <!-- this one is dynamic -->
    <a class="link">some button</a>  <!-- this one is dynamic -->

    <span>some text</span>  <!-- this one won't match the selector -->
    <span>some text</span>  <!-- this one won't match the selector -->

</div>

Live Example: http://jsfiddle.net/5jKzB/

So you bind a handler to some_container, and pass a selector to .delegate() that looks for "a.link" in this case.

When an element that matches that selector is clicked inside of some_container, the handler is invoked.

$('#some_container').delegate('a.link', 'click', function() {
    // runs your code when an "a.link" inside of "some_container" is clicked
});

So you can see that it doesn't matter when the "a.link" elements are added to the DOM, as long as the some_container existed when the page loaded.

The live()[docs] method is the same, except that the container is the document, so it processes all clicks on the page.

$('a.link').live('click',function() {
    // runs your code when any "a.link" is clicked
});