Elaine Marley
Elaine Marley

Reputation: 2213

jQuery events for appended content using .on?

I have appended content (using ajax) to my document and my events are not firing. I know this can be done using .live() but I read somewhere that it's deprecated now?

This is my code (it works fine on document ready, but not on the newly appended items):

$('li[id^="inv-"] a.close').on('click', function(){
 var item=($(this).closest("li[id^='inv-']")).attr('id');
 var id = parseInt(item.replace("inv-", ""));
 $.ajax({
   type: "POST",
   url: "ajax-invi.php",
   dataType: "html",
   data: "id="+idboda+"&idinv="+id+"&borrar=ok",
   success: function(data) {
     noty({"text":"El invitado ha sido borrado"});
     $("body").find('li#inv-' + id).remove();
   }
  }); 
});

And the items:

<ul>
  <li id="inv-39">
   <div class="row_field">
     <label>Adri</label>
     <a class="close" href="#invlist">Borrar</a>
   </div>                  
  </li>
  <li id="inv-40">
   <div class="row_field">
     <label>Marga</label>
     <a class="close" href="#invlist">Borrar</a>
   </div>  
  </li>
</ul>                

Upvotes: 1

Views: 162

Answers (2)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

try

$('ul').on('click','a.close', function(){
 var item=($(this).closest("li[id^='inv-']")).attr('id');
 var id = parseInt(item.replace("inv-", ""));
 $.ajax({
   type: "POST",
   url: "ajax-invi.php",
   dataType: "html",
   data: "id="+idboda+"&idinv="+id+"&borrar=ok",
   success: function(data) {
     noty({"text":"El invitado ha sido borrado"});
     $("body").find('li#inv-' + id).remove();
   }
  }); 
});

in this way you delegate the event handling to the ul which is present when the DOM is loaded and handles the events of elements added through AJAX. If the ul is not present when the dom is loaded you could delegate to the <body>tag

EDIT - live() it's actually a wrapper around on() (before it was a wrapper around delegate()) but delegates the event handling usually to the window which means that the event has to bubble up a lot. Taken from jQuery source

live: function( types, data, fn ) {
    jQuery( this.context ).on( types, this.selector, data, fn );
    return this;
},

Upvotes: 3

Smileek
Smileek

Reputation: 2797

$(document).on('click', 'li[id^="inv-"] a.close', function(){ 
//... 
});

So, you append event to some parent element, which looks for siblings which exists on page-loading and which will be appended in future.

Upvotes: 1

Related Questions