Usman Ahmad
Usman Ahmad

Reputation: 3

jQuery Clone element

I have cloned a element like

<div class = "button1"> Button1</div>
<div class = "text1Container">
    <div class="myButton"></div>
</div>
<div class = "text2Container"></div>

here my jQuery

$(".button1").click(function() {
    $( ".text1Container").clone().appendTo( ".text2Container" );
});

so now I want so set click function in "text2Container" but it did not work

//why not working
$(".text2Container .myButton").click(function() {
   alert('hello');
});

Upvotes: 0

Views: 79

Answers (2)

Kiran
Kiran

Reputation: 20313

You should use .on() to bind events for dynamically created html elements. Try this:

$(".text2Container").on('click','.myButton',function() {
   alert('hello');
});

And you have typo in your code. Replace button1 with .button1:

$(".button1").click(function() {
    $( ".text1Container").clone().appendTo( ".text2Container" );
});

DEMO

Upvotes: 3

Bic
Bic

Reputation: 3134

You aren't actually assigning a click to your button1. You are missing the . for class selector:

$(".button1").click(function () {
    $(".text1Container").clone().appendTo(".text2Container");

    $(".text2Container .myButton").click(function () {
        alert('hello');
    });
});

Note, the .myButton binding code has to be in with the .button1 click handler. You cannot bind an event to an element that does not exist yet.

See Fiddle

Upvotes: 0

Related Questions