Facebook social buttons with jQuery

Facebook social buttons are an easy way to insert Facebook's features into your website. If you connect to this page, you get for example the "Like" button that we're going to use in this tutorial. The point is: either you choose to use an iframe or FBML (Facebook Markup Language) you'll surely stumble on many validation errors, especially if you're using XHTML 1.0 Strict. So it's better to follow another approach, by using JavaScript and jQuery. So, given this markup:

<p id="fb-like"><iframe src="http://www.facebook.com/plugins/like.php?href=http%253A%252F%252Fonwebdev.blogspot.com&layout=standard&show_faces=true&width=450&action=like&font&colorscheme=light&height=80" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:450px; height:80px;" allowTransparency="true"></iframe></p>

you get this result, which is not a valid page. The first thing we need to do is to modify our markup by taking into account also the case when JavaScript is not supported, like this:

<p id="fb-like">

       <p><a href="http://www.facebook.com/plugins/like.php?href=http%253A%252F%252Fonwebdev.blogspot.com">Like</a></p>

By using the noscript element we make sure that our resource is still available when JavaScript is not supported or turned-off. Now it's time to add jQuery:

$(document).ready(function() {

  var $iframe = $('<iframe></iframe').attr(
                   'src': 'http://www.facebook.com/plugins/like.php?href=http%253A%252F%252Fonwebdev.blogspot.com&layout=standard&show_faces=true&width=450&action=like&font&colorscheme=light&height=80',                 
                 'scrolling': 'no',
                 'frameborder': '0',
                 'allowTransparency': 'true'
                 ).css({'border': 'none', 'overflow': 'hidden', 'width': '450px', 'height': '80px'});

Simply put, we've assembled our iframe by adding its own attributes and CSS styles. You can see the final result here.

Leave a Reply

Note: Only a member of this blog may post a comment.