Twitter provides a public JSONP feed for each user where we can find also the number of followers associated to each account (the followers_count property of the returned JSON object). Let's see how to fetch this datum with jQuery.
We can create the following plugin:
(function($) {
$.fn.twitterFollowers = function(options) {
var that = this;
options = $.extend({
username: 'gabromanato'
}, options);
var apiURL = 'https://api.twitter.com/1/users/show.json?screen_name=' + options.username + '&callback=?';
return that.each(function() {
$.getJSON(apiURL, function(data) {
$(that).text(data.followers_count + ' followers');
});
});
};
})(jQuery);
Our plugin accepts a Twitter username as its sole parameter. Bear in mind that you have to specify the callback string &callback=? in order to make the AJAX request work. If you don't specify this URL parameter, you'll get the Same Domain Policy restriction.
Here's an example:
$('#twitter-followers').twitterFollowers();
You can see the demo below.