Vaibhav
Vaibhav

Reputation: 1477

Clone a div with new ids and event handlers in jquery

I have a div, I want a new copy of div to be added somewhere in the page, but with new ids and new event handlers. New ids can be in the form "original id + _cloned". I am able to provide new ids, but I want all the event handlers which were there in original div, to be attached to new div which is mapped to new ids. Is there any way to do that using jQuery?

Upvotes: 0

Views: 1573

Answers (4)

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

You can use .clone( [withDataAndEvents] [, deepWithDataAndEvents] to copy the event handlers and data..

However I doubt if delegated events which are bound by ID would still work on cloned element.

Example: http://jsfiddle.net/Sfrm9/

$(document).on('click'. '#someId', function () { }); - would not work after you clone #someId and change it to #someId_cloned

As mcpDESIGNS mentioned here, you should map it to use class instead of id for the delegated handlers and then your clone should just work work fine.

Ex:

<div id="#someId" class="someClass" >Test</div>

JS:

$(document).on('click'. '.someClass', function () { });

instead of

$(document).on('click'. '#someId', function () { });

Upvotes: 1

Anthony Grist
Anthony Grist

Reputation: 38345

If you look at the jQuery documentation for the .clone() function, you'll see that there are two optional parameters to include data and event handlers for the element itself and for the elements descendants when cloning.

That will handle preserving the event handlers (as long as they're bound directly to that element, rather than being delegated), then you'll simply need to modify the id property of the resulting element. The following should do what you need:

$('#myid').clone(true).prop('id', function(i, oldId) {
    return oldId + '_cloned';
});

Upvotes: 2

gabitzish
gabitzish

Reputation: 9691

You could bind the events using a class for the divs. Then you can leave the same class to all divs that you need to respond to that event.

If your event is binded using an id selector, it will not work on your new div because you have to change its id, but it should work with classes.

Upvotes: 0

Greg Motyl
Greg Motyl

Reputation: 2545

.clone(true);

this way event handlers should be copied along with the elements

Upvotes: 1

Related Questions