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

lys916 picture lys916 · Mar 19, 2016 · Viewed 8.6k times · Source

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();
});

Answer

Sachin picture Sachin · Mar 19, 2016

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