Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add click events for dynamically appended elements using jquery?

here i'm able to remove box100 and box200 when clicked but not able to remove box1-box5 after appending it to the list. How do I select the appended elements?

https://jsfiddle.net/uhmgj8ky/4/

html
  <ul>
  <li class='list'>remove box100</li>
  <li class='list'>remove box200</li>
  </ul>
  <div class='box' box='box1'>add box1</div>
  <div class='box' box='box2'>add box2</div>
  <div class='box' box='box3'>add box3</div>
  <div class='box' box='box4'>add box4</div>
  <div class='box' box='box5'>add box5</div>

css
.box{
  height:50px;
  width:50px;
  border:2px solid blue;
  display: inline-block;
}
ul li{
    height:50px;
  width:50px;
  border:2px solid blue;
  display: inline-block;
  margin-right: 1px;
}

jquery
$('.box').on('click', function(){
    var txt = $(this).attr('box');
    $('ul').append("<li class='list'>remove "+txt+"</li>");
});

$('.list').on('click', function(){
    $(this).remove();
});
like image 751
lys916 Avatar asked Oct 27 '25 00:10

lys916


1 Answers

You should use event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. Both 

on()

 and 

delegate()

functions allow us to perform event delegation.

  


added a container class

 <ul>
  <li class='list'>remove box100</li>
  <li class='list'>remove box200</li>
  </ul>
<div class="box-container">
  <div class='box' box='box1'>add box1</div>
  <div class='box' box='box2'>add box2</div>
  <div class='box' box='box3'>add box3</div>
  <div class='box' box='box4'>add box4</div>
  <div class='box' box='box5'>add box5</div>
</div>

   $('.box-container').on('click',".box", function(){
     var txt = $(this).attr('box');
    $('ul').append("<li class='list'>remove "+txt+"</li>");
    });

     $('ul').on('click','.list', function(){
     $(this).remove();
     });

Update https://jsfiddle.net/uhmgj8ky/6/

For more on event delegation ,see video

like image 200
Sachin Avatar answered Oct 28 '25 18:10

Sachin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!