jQuery Trick #1: clone() vs clone(true)

This is my first post on jQuery Tricks. I had written some posts on jQuery Tips earlier but none on this category. So, I thought it’s right the time to write one now. 😉

Ok, let’s get back to business now.

Issue

So, few days back one of my colleague came across a strange issue. I am providing here a functional example to illustrate that issue.

HTML:

<b>Hello</b>
<p>, how are you?</p>

Now, here we have a simple markup with a single  b  tag and a  p  tag and the jQuery code like

jQuery:

$('b').click(function () {
    alert('Handler for .click() called.');
});

$('b').clone().prependTo('p');

In the above code :

  • Firstly, we are adding a  .click()  handler to all the  b  tags present in the DOM.
  • Then, we are creating a deep copy of the  b  element by using the DOM manipulation method called  .clone() . Deep copy means that it copies the matched elements as well as all of their descendant elements and text nodes.
  • Next, we are adding this new cloned content inside of and before the existing  p  element by using the DOM insertion method called .prependTo() .

Now, when clicked on the original  b  element, we get an alert, but when we clicked on the cloned  b  element, we didn’t get any alert. Also, there was no error in the browser console too. 😦

Demo:

Trick

The simple trick here to resolve this issue is to pass a boolean value true to the .clone() method.

$( 'b' ).clone(true).prependTo('p');

This boolean value indicates whether event handlers should be copied along with the elements. The default value is to the false . So, when we were calling the .clone() method without passing any boolean value, it was just copying the elements but not the event handlers attached to it. But, when we pass the value true , it copies both the elements and any event handler attached to it.

Demo:

That’s it! If you have any comments or suggestion or any queries about this post please add it in comments section. I would really appreciate it.

Happy Coding 🙂

Advertisements

6 thoughts on “jQuery Trick #1: clone() vs clone(true)

  1. Thanks so much for the post. Blogging, I think, is all about community and sharing something you think may be of value to others.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s