Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger event on cloned/inserted element in DOM?

I am not able to trigger event on element I clone/insert to the DOM.

Check the fiddle here.

HTML:

<div class="A">[THIS IS DIV A]</div>
<div class="B">CLICK TO CLONE DIV A</div>

jQuery:

$('.A').on("click",null,function() {    
    alert('DIV A CLICK');           
});

$('.B').on("click",null,function() {        
    $('.A').clone().insertAfter('.A');          
});

If I click on a cloned DIV A, nothing happens.

How can I trigger event on cloned element?

like image 842
Peter Lur Avatar asked May 08 '13 23:05

Peter Lur


People also ask

Do events also get copied when you clone an element in jquery?

Well the default implementation of the clone() method doesn't copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.

Does cloneNode copy event listeners?

Cloning a node copies all of its attributes and their values, including intrinsic (inline) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties (e.g., node.


1 Answers

There are two solutions I propose.

Firstly, and the better option in this case, would be to add the true argument to clone(), for example in this case it would be:

$('.A').clone(true).insertAfter('.A');

As first argument of clone() represents:

"A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false." - jQuery API section for clone().

This means all bound events will be kept on each cloned element.

jsFiddle here.


The second option, probably not the way to go for this example, would be to use on()'s event delegation feature:

"Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time." - jQuery API section for on().

In this case:

$(document).on("click", ".A", function() { ...

Now, every new element with the class .A will be have this click event attached to it, even cloned elements.

jsFiddle here.

like image 134
dsgriffin Avatar answered Nov 02 '22 06:11

dsgriffin