[philiptellis] /bb|[^b]{2}/
Never stop Grokking

Tuesday, October 27, 2009

Getting my twitter updates on this blog

I wanted my twitter updates to show up on the sidebar of my blog. At first I found that blogger already had a gadget for that, so I just included it. Unfortunately, this gadget loaded my timeline in an iframe. The iframe pointed to a script on someone else's domain, and every now and then that domain was unresponsive resulting in the rest of my page not loading.

It also did not work on Opera.

I decided to jump into twitter's API and figure out if I could get this to work on my own. I didn't bother with making it customisable, but if you want to reuse it, you'll need to change my username to your own. Here's what I did.

First, create a div that will hold my timeline:
<div id="twitter">
   <ul class="twitter-timeline">
   <div class="follow-me"><a href="http://twitter.com/bluesmoon">Follow me on twitter</a></div>

Put this wherever you want your timeline to go.

Next, write the Javascript that will draw the timeline. This is fairly simple:
function show_twitter(o) {
   var div = document.getElementById("twitter");
   var ul = div.getElementsByTagName("ul")[0];
   ul.innerHTML = "";
   for(var i=0; i<o.length; i++) {
       var li = document.createElement("li");
       li.innerHTML = o[i].text.replace(/@(\w+)/, "<a href='http://twitter.com/$1'>@$1</a>");
I put this at the start of the document, but you can put it anywhere before you make a call to the twitter API, which is the next step:
<script src='http://twitter.com/statuses/user_timeline.json?id=bluesmoon&count=5&callback=show_twitter'

A few things to note about this call:
  1. It's got my userid in it. It only works with userids that have public timelines
  2. count is limited to 5 items
  3. the callback parameter's value is the name of the function we defined in the previous step.
That's it. Put all this together and you have your latest 5 tweets on your blog. If your blogging software requires XML valid templates (like this blogger thing), then you'll need to either put your javascript inside a CDATA section or escape all quotes, &, < and >

Short URL: http://tr.im/bloggertwitter


October 27, 2009 6:37 AM

Isn't that what the twitter folks have at http://twitter.com/badges/ ?

October 27, 2009 7:00 AM


Post a Comment