Tuesday, April 10, 2012

Technogeekery: How to easily add Twitter and Facebook buttons to each post in Blogger

In the painful conversion effort from my aged Blogger template to a more modern version, I ran into several rather oppressive restrictions. For example, I wanted to retain the "Facebook Like" and "Tweet This" buttons with counts at the top, right-hand side of each and every post.

It does not appear Blogger allows you to do this without converting your entire template into HTML.

With my fondness for jQuery, I figured there had to be a way to add these buttons using only the Layout feature and a single HTML/Javascript gadget. After some experimentation, I discovered there does appear to be a way.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="fb-root"></div>
<script type="text/javascript">
(function(d, s, id) {
  var js, fjs = d.getElementsByTagName(s)[0];
  if (d.getElementById(id)) return;
  js = d.createElement(s); js.id = id;
  js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=Facebook App ID";
  fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

$(function() {
 $('.post-title').each(function(i, obj) {
  var o = $(this).find('a');
  var sURL = o.attr('href');
  var sTitle = o.text();
  if (sURL == null) {
   sURL = document.URL;
  var sTemp = "";
  sTemp += "<table border='0' style='float: right; margin: -39px -18px 3px 9px;'><tr><td>";
  sTemp += "<div style='text-align:left;padding:0 0 0 0;'><a class='twitter-share-button' data-count='vertical' data-text='"+sTitle+"' data-url='"+sURL+"' data-via='directorblue' data-related='' href='http://twitter.com/share'>Tweet</a><script src='http://platform.twitter.com/widgets.js' type='text/javascript'></"+"sc"+"ript></div>";
  sTemp += "</td><td>";
  sTemp += "<div class='fb-like' data-href='"+sURL+"' data-send='false' data-layout='box_count' data-width='0' data-show-faces='false'></div>";
  sTemp += "</td></tr></table>";
  var p = $(this).parent().find('.post-body');
  p.html(sTemp + p.html());

You may need to update the margins (in red), because each template may have some different offsets. Obviously, you'll need to use your own Facebook App ID (in blue).

Good luck! No warranty is either express or implied, and any damage you do to your template is your own dang fault!


Beth Austin said...

But where do I post all that code to enable the Twitter/Facebook buttons? My layout page has no place for me to insert text like that.

directorblue said...

From layout, add a single HTML/Javascript widget/gadget (can't remember what they call it) anywhere on the page.