Thomas T
Thomas T

Reputation: 2371

how to attach jquery event handlers for newly injected html?

How would I use .on() if the HTML is not generated yet? The jQuery page says

If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

But I'm not really sure how to do that. Is there a way to "reload" the event handler?

So if I had

$(document).ready(function(){
    $('.test').on('click', function(){
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });
generatePage();
});

where generatePage() creates a bunch of divs with .test, how would I rebind .on()?

I'm aware similar questions have been asked, but I didn't find what I was looking for after a quick search.

Upvotes: 12

Views: 7364

Answers (1)

T. Junghans
T. Junghans

Reputation: 11683

Use .on like in the example below. One can presume that the body-tag is always available so it's safe to attach the event handler to body and delegate the events to the selector, in this case .test.

$(document).ready(function(){
    $('body').on('click', '.test', function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

Or if generatePage() is also generating the html, head and body tags use document as your selector.

$(document).ready(function(){
    $(document).on('click', '.test', function(){ // Make your changes here
        var id = $(this).attr('id');
        console.log("clicked" + id);
    });

    generatePage();
});

According to the jquery documentation .on accepts the following parameters:

.on( events [, selector] [, data], handler(eventObject) )

Including selector is described as follows:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Upvotes: 24

Related Questions