Reputation: 49
I'm building a simple project something like Twitter but very simple :) There are a lot of tweets on user's homepage (timeline). So every tweet has favorite button. When user clicks to favorite button, it sends AJAX request to the server to store favorited tweet. So favorite buttons are somethings like this:
<a href="#" id="1"><i class="icon-star-empty"></i></a>
<a href="#" id="2"><i class="icon-star"></i></a>
<a href="#" id="3"><i class="icon-star-empty"></i></a>
...
...
I use the following JavaScript to send AJAX request:
$("i").on("click", function() {
if ( $(this).hasClass("icon-star-empty") ){
ajaxURL = "/setFavorite"
} else{
ajaxURL = "/removeFavorite"
}
var linkID = $(this).parent().prop("id");
var obj = $(this);
$.ajax({
url: ajaxURL,
type: "POST",
data: {quoteID : linkID},
success: function() {
obj.hasClass("icon-star") ? obj.removeClass("icon-star").addClass("icon-star-empty") : obj.removeClass("icon-star-empty").addClass("icon-star");
}
});
})
Since there are a lot of tweets, I set Infinite Scroll Plugin. AJAX requests work well when I didn't set Infinite Scroll. But when I set, those AJAX requests don't work for those tweets which are loaded via Infinite Scroll. I mean, when I click to the favorite button of the tweets which are loaded via Infinite Scroll, they don't send AJAX request to the server. But AJAX requests work with the tweets which are loaded via default HTML not Infinite Scroll.
So my question is how can I solve this problem? How can I send AJAX request for the tweets which are loaded via Infinite Scroll?
Thanks in advance.
Upvotes: 0
Views: 808
Reputation: 318478
$('selector').on('event', callback)
only binds events for the elements that exist at the time where the selector is processed. However, the infinite-scrolling code loads new elements later so no event is bound for them.
The solution is using a delegate:
$('selector').on('click', 'i', function() {
// do stuff
});
selector
needs to be a parent element that contains all your (dynamically added) i
elements.
Upvotes: 1