Initially thought of just to write a small article on Facebook XFBML Like Widget but when I started writing with the demo part then realize that other things also needs explanation so now divided into 3 parts and would try to explain them individually.

This article is going to cover following topics with the final demo in the last with all the integration in ones.

  • Facebook XFBML Like Widget
  • YouTube JavaScript API
  • jQuery AJAX

One of the problems comes when you try to make dynamic facebook like button to show the count based upon the particular URL and parse it.

Facebook Like Widget:

 

 

The Like button lets a user share your content with friends on Facebook. When the user clicks the Like button on your site, a story appears in the user’s friends’ News Feed with a link back to your website

There are two Like button implementations: XFBML and Iframe. The XFBML version is more versatile, but requires use of the JavaScript SDK. The XFBML dynamically re-sizes its height according to whether there are profile pictures to display, gives you the ability (through the JavaScript library) to listen for like events so that you know in real time when a user clicks the Like button, and it always gives the user the ability to add an optional comment to the like

It has multiple attributes like href, layout, width, action etc. you can get the complete list at http://developers.facebook.com/docs/reference/plugins/like

Of course you should always try to use XFBML button only because it gives you more options and control over Iframe facebook like but again it requires Facebook JavaScript SDK in order to make it work.

Facebook JavaScript SDK:

 

 

It is open source and available on GitHub [http://github.com/facebook/connect-js]

JavaScript SDK is also necessary to use the XFBML version of facebook like.

There are 2 ways to call JavaScript SDK

  1. Just write this line in your page head section and use it[sourcecode language=’html’][/sourcecode]
    1. Another way is to load asynchronously so it does not block loading other elements of your page:[sourcecode language=’html’]

      [/sourcecode]

      Anyway there is already enough information about the SDK, you always can go and check at http://developers.facebook.com/docs/reference/javascript/

      YouTube JavaScript API:

       

      The JavaScript API allows users to control the YouTube chromeless or embedded video players via JavaScript. Calls can be made to play, pause, seek to a certain time in a video, set the volume, mute the player, and other useful functions.

      You can find more detail at http://code.google.com/apis/youtube/js_api_reference.html

      Not going to explain it further otherwise it will eat up the entire article if I start writing it here 🙂

      jQuery API:

       

      No need to explain this wonderful API on the planet, jQuery has all the things which you require for any website/portal starting from traversing, event handling, animation and AJAX though there are other robust frameworks too to compete jQuery like Dojo, ExtJS, Prototype, YUI etc.

      We will use the jQuery $.ajax wrapper which will serve our purpose to get the JSONP data from the YouTube to make video gallery and then we push the Facebook XFBML Like in the picture to get the set the like count.

      So now let’s start coding and see all things working together, have got the code snippets from YouTube API [http://code.google.com/apis/youtube/2.0/developers_guide_json.html] and converted to jQuery code.

      [sourcecode language=’html’]
      < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">




‘);
}
html.push(”);
document.getElementById(‘videos’).innerHTML = html.join(”);
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url, false);
}
}

$(function(){
$.ajax({
type: “GET”,
url: “http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5”,
cache: false,
dataType:’jsonp’,
success: function(data){
showMyVideos(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert(“Not able to fetch the data due to feed unavailability!!!”);
}
});
})

 

Mohammed Arif Blog Facebook Likes

 

 

[/sourcecode]

So what we doing here is fetching YouTube data based upon some filter criteria like most_viewed, max-results and format etc in the jQuery URL parameter, there are number of criteria available in gdata feed and the dataType is JSONP which works cross domain and of course using GET method to fetch video feed.

[sourcecode language=’js’]
$(function(){
$.ajax({
type: “GET”,
url: “http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed?time=this_week&alt=json-in-script&max-results=5&format=5”,
cache: false,
dataType:’jsonp’,
success: function(data){
showMyVideos(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert(“Not able to fetch the data due to feed unavailability!!!”);
}
});
})
[/sourcecode]

Then we hit the success method when the request succeeds then we send the data to the next method showMyVideos(data) to parse and build the DOM.

[sourcecode language=’js’]
function showMyVideos(data) {
var feed = data.feed;
var entries = feed.entry || [];
var html = [‘

    ‘];
    for (var i = 0; i < entries.length; i++) { var entry = entries[i]; var title = entry.title.$t.substr(0, 20); var thumbnailUrl = entries[i].media$group.media$thumbnail[0].url; var playerUrl = entries[i].media$group.media$content[0].url; var videoId = playerUrl.substr(playerUrl.indexOf('v/')+2, 11); playerUrl = "http://www.youtube.com/v/" + videoId; html.push('
  • ‘,
    ‘, ”);
    }
    html.push(‘

‘);
document.getElementById(‘videos’).innerHTML = html.join(”);
if (entries.length > 0) {
loadVideo(entries[0].media$group.media$content[0].url, false);
}
}

[/sourcecode]

Now we just need to read the data and manipulate the DOM and attach loadVideo() method with the specified URLs and also load the first video using our loadVideo(playerUrl, autoplay) method which takes 2 parameters which takes playerUrl and autoplay which we need to send to the SWFObject embedSWF() to build and run the videos.

[sourcecode language=’js’]
function loadVideo(playerUrl, autoplay) {
swfobject.embedSWF(
playerUrl + ‘&rel=1&border=0&fs=1&autoplay=’ +
(autoplay?1:0)+’&version=3′, ‘player’, ‘585’, ‘355’, ‘9.0.0’, false,
false, {allowfullscreen: ‘true’});

/*Parse the facebook like button*/
$(‘#like’).html(‘‘)
if (typeof FB != “undefined”){
FB.XFBML.parse(document.getElementById(‘like’))
}
}
[/sourcecode]

loadVideo() is the main method to do all things including build the dynamic Facebook like widget, this is the key to write this article because making dynamic Facebook Like widget may create some problems.

Anyway now we have the solution with us, so we already have DIV id=”like” in our HTML, we just writing XFBML on run time to parse the Facebook Like button and get and set the video count based upon the particular video.

[sourcecode language=’js’]
/*Parse the facebook like button*/
$(‘#like’).html(‘‘)
if (typeof FB != “undefined”){
FB.XFBML.parse(document.getElementById(‘like’))
}
[/sourcecode]

And then we check whether FB object exist or not and if it does then parse the XFBML tag and show the count if you like it.

Here you go to see the complete code and demo

Privacy Preference Center

Verified by MonsterInsights