JavaScript badge to present Twitter reactions to a certain URL in your own web site

With a blog it’s great getting comments, but as any blogger need to realize, there are other channels that people like to express their reactions in to – especially Twitter.

Background

Therefore, I wanted a nice way to implement reactions on Twitter to my blog posts, so everyone reading could see it all in the same context. Some time ago (maybe a year) I found the BackType Connect plugin for WordPress.

All good and well, till it stopped working a few months ago. I went through all of my settings, checked server and plugin rights etc to see where the problem was. I also e-mailed the BackType support team and never got a reply. Eventually, by chance, I found a blog post by the Backtype team proclaiming that they had retired their WordPress plugin, without any notice whatsoever to all of its users.

What bugs me even more is that you can still download the plugin from their own web page without any information about this, and it is still easy to find in WordPress own listing of plugins.

That is really really bad, and definitely not a responsible way to handle code. I don’t ask for them to support it anymore, I’m sure they had good reasons to move on and focus on other things. But, not letting end users know and still having it publicly available really sucks, in my opinion.

Looking at options

Therefore, I needed to start looking at options. Something that is really popular these days is DISQUS for general comment handling, handling things such as Twitter reactions etc. However, I really didn’t feel attracted by syncing comments to another service, getting loads of scripts and invalid code in my blog generated by them etc (I tried it on my blog, and besides from all the superfluous code, it broke my entire layout with a generated stray end div tag…).

I wanted something really lightweight with only the necessary code to show Twitter reactions, so I decided to implement it as a JavaScript badge, generated from JSON data. Therefore, I looked directly at the Twitter Search API where I could get this data. All worked good and well, but Twitter Search only supports searching from today and a week back in time, and naturally I wanted reactions from a longer timeline than that.

That’s when I started looking at Topsy and their Otter API. The really good thing about Topsy is that it supports finding tweets all the way back to 2008 and getting them returned as JSON, which is awesome!

Using Topsy/Otter API to find trackbacks

Now when I had found a service that would deliver what I needed, I delved deeper into it to create my Twitter reactions JavaScript badge. It is based on JSONP, which is returned JSON data, but wrapped with a function call, so it would call a function in my web site with the JSON data so I could iterate over it and present the tweets. Like this:

	twitterReactions({"Data": "My name is JSON"});

Getting the JSONP code is as simple as including a script element in your web page, set its src to the Otter API URI and pass the URL you want Twitter reactions to as a parameter:

	<script src="http://otter.topsy.com/trackbacks.js?callback=twitterReactions&perpage=100&url=http://robertnyman.com/2010/10/22/introducing-html5-web-sockets-taking-bidirectional-communication-on-the-web-to-the-next-level-2/"></script>

As you can see in the above code, I have three parameters:

callback
The JavaScript function in my page that I want to use to process the JSON data.
perpage
How many results per page (i.e. total results) I want in the returned JSON. I want it all in the same page, and currently the maximum supported number is 100 tweets. A shame with that limitation right now (I think Twitter’s own limit is 1500), but I don’t have many posts with over 100 Twitter reactions, so for now I can live with that.
url
The URL, i.e. address to my blog post, that I want to find Twitter reactions for.

There are also a number of other parameters if you want to tweak things even more.

Creating the JavaScript badge

Now that we know how to get Twitter reactions as JSONP, let’s look at how we create our badge to present those tweets. What we need first is an HTML element in which we want to show those reactions:

	<div id="twitter-reactions"></div>

As you see, I leave this element empty so nothing is shown if it fails – however, if you want to you could have some fallback content there.

Then, in your web page, or preferably in an included JavaScript file, add the twitterReactions function we specified before to handle the response:

function twitterReactions (json) {
	// Checking the JSON response
	var results = json.response.list;
		
	// If there are any results, iterate over them			
	if (typeof results !== "undefined") {
		var resultsLength = results.length,
			twitterReactionsPresenter = document.getElementById("twitter-reactions"),
			twitterReactionsHeader = document.createElement("h3"),
			tweets = '
    ', twitterReactionsText = resultsLength + " Twitter reaction" + ((resultsLength > 1)? "s" : ""), current, currentAuthor, tweet; // Creating header before tweets container twitterReactionsHeader.id = "twitter-reactions-header"; twitterReactionsHeader.innerHTML = twitterReactionsText; twitterReactionsPresenter.parentNode.insertBefore(twitterReactionsHeader, twitterReactionsPresenter); // Iterating over all tweets for (var i=resultsLength-1; i>=0; i--) { current = results[i]; currentAuthor = current.author; tweet = '
  • '; tweet += ''; tweet += '' + currentAuthor.nick + " (" + currentAuthor.name + ")" + "
    "; tweet += current.date_alpha; tweet += '
    ' + current.content.replace(/(http:\/\/[\w\.\d%\/\-\_]+)/gi, '$1') + '
    '; tweet += '
  • '; tweets += tweet; } tweets += '
'; // Apply all tweets into the tweet presenting element twitterReactionsPresenter.innerHTML = tweets; } }

I think that code is pretty self-explanatory. It checks the JSON data if there were any results, and if yes, it creates a heading and applies it before the Twitter reactions HTML container element with a reaction count. Then it iterates over all the reactions and creates HTML elements for them and when it’s done, it applies the entire HTML chunk into the web page.

I wanted this very simple code to be JavaScript-library agnostic, but you could of course use a JavaScript library or native DOM methods (*shivers*) to create the elements as real DOM elements instead of as an HTML string. For me, though, this is all good.

Then, as we saw above, after our twitterReactions function has been declared, we include the script file to get the JSONP data:

	<script src="http://otter.topsy.com/trackbacks.js?callback=twitterReactions&perpage=100&url=http://robertnyman.com/2010/10/22/introducing-html5-web-sockets-taking-bidirectional-communication-on-the-web-to-the-next-level-2/"></script>

And there we have it! A fully functional JavaScript badge to get Twitter reactions to any URL we put in.

Demo of the Twitter reactions JavaScript badge

You can take a look at the demo of the Twitter reactions JavaScript badge and see how it gets reactions for a certain URL. Just take the code in this blog post or the demo page and create your own badge and tweak it to your own needs.

Happy getting-twitter-reactions day! :-)

Posted in Developing,JavaScript,Technology |

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>