6

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?

Adam
  • 9,189
  • 15
  • 46
  • 62
  • http://stackoverflow.com/questions/6658752/jquery-click-event-doesnt-work-on-dynamically-generated-elements/14533243?noredirect=1#comment22575409_14533243 – Roko C. Buljan Apr 07 '13 at 22:35
  • Wrong. Read the documentation for `.on()`. – SLaks Apr 07 '13 at 22:36
  • `.on()` _does_ work if you pass the appropriate parameters. Did you read the doco? If you read the [doco for `.live()`](http://api.jquery.com/live/) it tells you how to convert to `.on()`... – nnnnnn Apr 07 '13 at 22:36
  • Yes, I've ready the docs but I'm not able to get it functioning in the same way. What the "appropriate parameters"? – Adam Apr 07 '13 at 22:41
  • Got it working, realized it had to be applied to the document level like this: $(document).on("click", "#ButtonID", function(e){ – Adam Apr 07 '13 at 22:43
  • I could be wrong, but I think `$.click()` uses the latest. –  Apr 07 '13 at 22:52

2 Answers2

15
$(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.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Paul Grime
  • 14,970
  • 4
  • 36
  • 58
3

delegate is far efficient than on handler

$(document).delegate('click', "selector", function() {
    //your stuff
});
Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55
Hiren Kavad
  • 111
  • 1
  • 10