What happens to event when you clone element using jQuery

jQuery has a method called "clone()". As the name suggests, it creates a exact copy of the element. The .clone() method performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.


As for example, I have defined a div and I want to make a copy/clone of the div.
<div id="dvClickme" > Click Me </div>
As you can see in below code, On click of button (btnClone) I am making clone of the div and appending it to body using the clone() method. I have also defined a click method on the div element so when you click on the div, it shows an alert box with the specified message.
$(document).ready(function(){
    $("#dvClickme").bind('click', function(){
        alert('You clicked me..');
    });

    $("#btnClone").bind('click', function(){
       $('#dvClickme').clone().appendTo('body');
    });
});    
//Code Ends           ​
First, check the click event of the div and then click on the button to clone the div.

See result below.



Have you noticed that when you click on the cloned div (gets added when you click on "Clone Div" button), it doesn't show the alert box. Haven't you? Try again the above demo.

Okay, so the click event is not working when you cloned the element. So what happened to the click event? 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.

$("#btnClone").bind('click', function(){
   $('#dvClickme').clone(true).appendTo('body');
});
//Code Ends           ​
Now you will see that on both the div, when clicked alert box is displayed.

See result below.



Hope you find it useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..