Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event for elements added to DOM dynamically

Tags:

jquery

dom

click

Before jQuery 1.8 I was able to use .live() to fire when a button was clicked that was dynamically inserted by jquery.

Now, .on() and .bind() both do not work for elements added to DOM after the page was loaded.

What are the options now?

like image 776
Adam Avatar asked Apr 07 '13 22:04

Adam


2 Answers

$(parent_element).on("click", child_selector, function(evt) {
});

http://api.jquery.com/on/#direct-and-delegated-events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

like image 59
Paul Grime Avatar answered Oct 18 '22 11:10

Paul Grime


delegate is far efficient than on handler

$(document).delegate('click', "selector", function() {
    //your stuff
});
like image 3
Hiren Kavad Avatar answered Oct 18 '22 10:10

Hiren Kavad