Reputation: 1616
I have a tag when clicked alerts the data-value of the tag. It works fine , but doesn't works when i click on dynamically created elements.
<img id="no_p_fav" src="http://localhost:8000/icons/non_star.png">
Below is how i create dynamic elements
$('.all_candidate_bar').prepend('<div id = "icons"> <a class = "favorite" data-value = "'+data.msg.id+'" > <img id = "no_p_fav" src="{{url("/icons/non_star.png")}}" ></img></a></div>');
Below function doesn't work on dynamically created elements but works fine on elements which were there when the page was loaded.
$(document).ready(function(){
$('.favorite').on('click',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});
I have also tried this
$('#icons').on('click','a.favorite',function(){//myFunction});
$('a').on('click','.favorite',function(){//myFunction});
How do i make it work for elements for both dynamic and static elements ?
Upvotes: 0
Views: 86
Reputation: 8409
change your function like this way
$(function(){
$(document).on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
Upvotes: 0
Reputation: 11102
Since the #icon
is also created dynamically you cannot use event delegation against it, you need a higher level element that is there since the beginning, body
for instance:
$('body').on('click','.favorite',function(){//myFunction});
The a
also won't work, since the event is not delegated in this case, it is accessing the element itself
$('a').on('click','.favorite',function(){//myFunction}); // won't work
Upvotes: 3
Reputation: 50291
For dynamically created element you need to to delegate the event $(document).ready(function(){
$('body').on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});
Upvotes: 0
Reputation: 327
Try this Code:
$(document).ready(function(){
$(document).on('click','.favorite',function(){
var candidate_id = $(this).data('value');
alert(candidate_id);
});
});
Upvotes: 0