Reputation: 3
I'm having a little problem: I'm trying to write a jQuery function that loops over all divs which have a specific class and populates them with Facebook's Like count (the required URL is in the rel
attribute). The problem is that it only takes effect on the last item for some reason.
HTML:
<div class="facebook_likes" rel="http://www.somesite.com/"></div>
<div class="facebook_likes" rel="http://www.somesite2.com/"></div>
<div class="facebook_likes" rel="http://www.somesite3.com/"></div>
JS:
function getLikes() {
jQuery('.facebook_likes').each(function(){
currentdiv = jQuery(this);
url = currentdiv.attr('rel');
jQuery.getJSON('http://graph.facebook.com/'+url,function(data) {
currentdiv.text((data.shares || 0)+' Likes');
});
})
}
Thanks!
PS: I'm calling the function on document ready. Fiddle at: http://jsfiddle.net/Mjzpm/1/
Upvotes: 0
Views: 6898
Reputation: 440
At first you have to create a username of your page(see under your page name @username. Just click it...)
Then goto https://developers.facebook.com/tools/explorer/ and get an access token key
Then script something like that
function facebookLikesCount(access_token)
{
var url = "https://graph.facebook.com/voucherin.ukbd?fields=likes&access_token="+access_token+"";
$.getJSON(url,function(json){
alert(json.likes);
});
}
facebookLikesCount('your accesstoken');
Upvotes: 0
Reputation: 3695
The answer is very simple.
function getLikes() {
jQuery('.facebook_likes').each(function(){
var currentdiv = jQuery(this);
var url = currentdiv.attr('rel');
jQuery.getJSON('http://graph.facebook.com/'+url,function(data) {
currentdiv.text((data.shares || 0)+' Likes');
});
})
}
You need to initialize currentDiv and url on every loop through. By the time the first getJSON completes, the currentDiv/url are now equal to the last value that those two variables were set to.
Upvotes: 1