What happens to event when you clone element using jQuery
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.