KroniK907
KroniK907

Reputation: 361

re-applying jquery to cloned objects

What is the proper way to re-apply jquery to objects which are cloned??

I have an example I rigged up in jsfiddle here: http://jsfiddle.net/49o6arLu/16/

<div class="hidden element-holder">
    <div class="element">
        <div class="button">Button</div>
        <div class="green-square"></div>
    </div>
</div>
<div class="element">
    <div class="button">Button</div>
    <div class="green-square"></div>
</div>
<div class="clear"></div>
<div class="add-element">Add Element</div>

$('div.button').click(function(event) {
    if($(this).parent().children('.green-square').is(':visible')) {
         $(this).parent().children('.green-square').hide();
    }else{
         $(this).parent().children('.green-square').show();
    }
});

$('div.add-element').click(function(event) {
    $('div.element-holder').children('div').clone().insertAfter($('div.element-holder'));
});

As you can see, the initial displayed box and button work just fine. However, When you add another element the new element button does not work anymore.

I understand why I have this problem, however I don't know the proper way I should go about re-applying the Jquery to the new elements which are cloned.

Can someone provide a solution to the jquery and provide some explanation as to what you did?

Thanks!

Upvotes: 2

Views: 50

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337570

You can save the need to re-apply the handler to all the appended elements by having a single delegated click handler on a common parent element.

First of all amend your HTML to include the container, in this case #element-container:

<div class="hidden element-holder">
    <div class="element">
        <div class="button">Button</div>
        <div class="green-square"></div>
    </div>
</div>
<div id="element-container">
    <div class="element">
        <div class="button">Button</div>
        <div class="green-square"></div>
    </div>
    <div class="clear"></div>
</div>
<div class="add-element">Add Element</div>

Then you can amend the Add Element button to append to that container:

$('div.add-element').click(function (event) {
    $('div.element-holder').children('div').clone().appendTo('#element-container');
});

Finally you can add the delegated event handler to the new #element-container. Note that I also shortened the logic using toggle() and siblings():

$('#element-container').on('click', 'div.button', function (event) {
    $(this).siblings('.green-square').toggle()
});

Example fiddle

Upvotes: 2

Alon Brimer
Alon Brimer

Reputation: 111

In order to copy event handlers you should send true in the clone method:

$('div.add-element').click(function(event) {
$('div.element-holder').children('div').clone(true).insertAfter($('div.element-holder'));});

Upvotes: 1

Related Questions