AJAX Friendly, jQuery Facebook Like Buttons

Facebook Like buttons are easy enough to integrate, but with enough caveats it can be difficult to maintain a best-practices approach. A recent project required a slew of Like buttons on one page, each interacting with a different article in the app. All the buttons had to be pure JavaScript, and they had to work smartly with AJAX pagination.

The method we chose was to loop through the anchor tags that led to a “Likeable” page, using their attributes to build up the Like buttons. Then we created the Facebook DOM elements and pushed them into the right spot. If a user had JavaScript disabled, she wouldn't be bothered by obsolete markup that does nothing, but with JavaScript enabled, she would see a highly dynamic index of Like buttons.

First thing we do is wrap everything in a function called setFacebookLike(). This is important so that you can attach it to the callback of an AJAX pagination request, thus ensuring that your Like buttons survive any type of DOM tinkering.

Inside the function, attach some Facebook attributes to the HTML tag. Next, remove and/or empty out the contents of the Facebook Like divs that have been left over, if there are any. Finally we're in a position to loop through the anchors.

With this syntax, the “this” in the function is the anchor we're making a button for, so all its attributes are readily available to us. (I've broken up initializing the URL variable to ensure it works with staging servers, which often have different URL roots and databases, and in this case, different articles to like.)

Once we store the like button markup into a variable like this…

…we can shove into the DOM anywhere, using our $(this) anchor as a starting point:

Finally, we pull in the Facebook JavaScript parser to turn our existing code into an iFrame:

Now, you call setFacebookLike().