0

I have HTML list:

<ul>

contains initial items of:

<li>

I have added new items dynamically to that list. Old items are responding very well , but the new ones cannot be triggered for the same event.

I am using (.on) event as per JQuery documentation to trigger the current and future elements. But still not responding.

$(".favorite-btn").on("click",function(){
    alert("Yes!");              
 });

Could you help ?

Hatem
  • 349
  • 2
  • 12

2 Answers2

2

You need to use event delegation for attaching events to dynamically added elements:

$("ul").on("click",'.favorite-btn',function(){
 alert("Yes!");              
});
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

You need to use event delegation for dynamically added DOM elements as shown below :-

$(document.body).on("click",".favorite-btn",function(){
    alert("Yes!");              
});

OR

$("ul#id").on("click",".favorite-btn",function(){
    alert("Yes!");              
});
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69