Lil’ Twitter Hack

If you’re a Twitter user (and it’s the “in” thing to do these days, or so I hear) do you have your latest tweets displayed on your web site?

It’s easy. I prefer the HTML widget because you can play with it a bit more within your own design, etc: http://twitter.com/widgets/html_widget

I’ve made a quick hack to the JavaScript that comes with the widget:

  1. No replies – I didn’t want it to display replies to other Twitter users. After all, the people seeing these messages on my site will have no idea who these other users are, or probably even what the strange @ symbol means.
  2. Wrap the links – Putting the full URL for the links seemed archaic, so I took the URL for links out of the message, and instead wrapped the whole Tweet in a link, if there was a link in it.

It wasn’t difficult but I thought I’d share the code in case you want to do the same!

function twitterCallback(tweets) {
  var statusHTML = [];
  for (var i=0; i<tweets.length; i++){
    var username = tweets[i].user.screen_name;
        //Skip replies
        if (tweets[i].text.search(/^@/) != -1) {
            continue;
        }
        //If there's a link, remove URL from message and the make whole tweet a link
    var url = tweets[i].text.match(/((https?|s?ftp)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g);
    var status = tweets[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, '');
        if (url) {
            status = '<a href="' + url + '">' + status + '</a>'
        }
        //Push the Tweet into the status box
    statusHTML.push('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+tweets[i].id+'"><em>'+relative_time(tweets[i].created_at)+'</em></a></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

In order to use it, you can enclose it in script tags like this:

<script type="text/javascript">
--Script Here--
</script>

In my case, I put it in a separate .js file so it can be shared by different pages.

Let me know if it’s of use.