Tag Archives: append

Attach event to dinamically added HTML elements with jQuery

If you have an event handler defined like this in JavaScript:

$("a[product-id]").click(edit_product);

function edit_product(event) {
    ...
}

After adding elements (nodes) dinamically (after an AJAX call for example) that fit that selector to the HTML DOM with .append() or .html(), the event won’t work on them. That’s because the element was added AFTER calling the event method that links to the function we want to execute.

To ensure all elements that fit the selector will trigger the event you have to use .on() for example with $(document) as the ancestor:

$(document).on('click', "a[product-id]", edit_product);

jquery-logo

Ref: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements