0

I am trying to add a button dynamically - the first button works but not the others. I was previously using the live function, but jQuery 1.9.1 removed that function. What should I do to get the newly added buttons to work?

HTML Code:

<div class="take">
    <p>this is the para</p>
    <button class="test">copy</button>
</div>

jQuery Code:

$('.test').on('click', function() {
    var a = $(this).parent();
    new.clone().insertAfter(a);
})

Here is the jsfiddle.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Selvamani
  • 7,434
  • 4
  • 32
  • 43

3 Answers3

7

Passing true in clone will solve your problem - jsfiddle

$('.test').on('click', function() {
    var o = $(this).parent();
    o.clone(true).insertAfter(o);        
})

Note: new is a keyword in JavaScript so don't use it as a variable.

fragilewindows
  • 1,394
  • 1
  • 15
  • 26
Anoop
  • 23,044
  • 10
  • 62
  • 76
  • To give context, passing true to `.clone()` makes it a deep copy (with events). That's why re-adding it works (though doesn't actually rely on using `.on()` correctly/as intended). – Brad Christie Apr 09 '13 at 14:58
2
$(document).on('click', '.test', function() {
    var o = $(this).parent();
    o.clone().insertAfter(o);   
});

Instead of document use rather a non-dynamic parent ID selector

http://jsfiddle.net/uk6Bh/1/

To visualize:

$('#non-dynamic-parent').on('event', '.dynamic-delegated-element', function() {

http://api.jquery.com/on/ says:

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
1

You want to use .on() (demo):

$(document).on('click', '.test', function() {
    var o = $(this).parent();
    o.clone().insertAfter(o);
})
jmar777
  • 38,796
  • 11
  • 66
  • 64
  • why go as far as document if you can find a closer static parent? thats a lot of traversing no? – David Chase Apr 09 '13 at 15:01
  • 1
    It's still extremely cheap (click events are rare, bubbling is fast). Also, no markup further up the DOM tree was provided to incorporate in an answer. – jmar777 Apr 09 '13 at 15:06