Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 830
Buzzztube Avatar asked Mar 10 '26 10:03

Buzzztube


1 Answers

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>
like image 104
Martin Avatar answered Mar 12 '26 22:03

Martin