Buzzztube
Buzzztube

Reputation: 77

Create clone on another function with jquery

It shows a message 'Hi' when I click on 'ShoW', But when I click on the next option 'ShoW', it does not show a message.

$('.btn').on("click", function () {
    alert('Hi');
    $('.box .btn').remove();
    $('.btn').clone().appendTo('.box'); 
    return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>

What code should I add for JS?

Upvotes: 3

Views: 154

Answers (2)

AMYR
AMYR

Reputation: 182

You have to set event once more again after clone. then, you can declare your event callback as a function, and set event again after cloning on the cloned element, like this:

function appendShowButton() {
    alert('Hi');
    $('.box .btn').remove();
    var newEl = $('.btn').clone().appendTo('.box');
    newEl.on('click', appendShowButton);
    return false;
}

$('.btn').on("click", appendShowButton);

Upvotes: -1

Martin
Martin

Reputation: 16433

This is because the event handler you created is bound to objects that existed when it was created:

$('.btn').on("click", function () {

This will only work for .btn elements that were already available at the time this line of code ran - it is not evaluated by jQuery again.

Instead, use this format for binding the event, which will pick up dynamically created elements:

$(document).on('click', '.btn', function () {

Seen here in this working snippet:

$(document).on('click', '.btn', function () {
    alert('Hi');
    $('.box .btn').remove();
    $('.btn').clone().appendTo('.box'); 
    return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>

Upvotes: 2

Related Questions