3

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?

Liam
  • 27,717
  • 28
  • 128
  • 190
Buzzztube
  • 77
  • 5
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Liam Aug 02 '21 at 14:10

2 Answers2

2

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>
Martin
  • 16,093
  • 1
  • 29
  • 48
-1

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);
AMYR
  • 124
  • 4