Add a twitter feed to your site using jQuery

Here’s a some simple java script to include a twitter feed for a particular user’s timeline into a web page. It assumes you’ve got jQuery (version  1.2 or higher) already installed.

function showTweets (data) {
  $('#feed').empty();
  for (var tweet in data) {
    $('#feed').append('<p>'+data[tweet].text+'</p>');
  }
}

$( function () {
  var user = 'TWITTER_USERNAME'; //the twitter user name of the person who's tweets you want to include
  var no_tweets = 10; //the number of tweets to fetch
  $.getScript("http://twitter.com/statuses/user_timeline/"+user+".json?count="+no_tweets+"&callback=showTweets")
})
I’ve also added a div with the id “feed” in my html to contain the tweets like this:
<div id="feed">
<p>Loading Tweets...</p>
</div>
The callback function showTweets empties this div before filling it with the 10 most recent tweets, so that “Loading Tweets…” message vanishes once the script has done its work.
Simple but effective no? Well I though it was pretty clever.
Note that the jQuery getScript() method can fetch javascript across domains since jQuery version 1.2.

Tags: , ,

3 Responses to “Add a twitter feed to your site using jQuery”

  1. Russ Says:

    Incidentally, I just implemented this method of getting tweets onto the planet-nifty sidebar and, as a special treat, I installed jquery.linkkify (http://code.google.com/p/jquery-linkify/) and added this line at the end of the above script:
    $(‘#feed’).linkify();

    Now it automatically creates links from any URI’s in the tweet text. Neat huh?

  2. Tim Says:

    Very cool stuff :)

    Just needs some sort of syntax highlighting plugin – should be plenty for WP, methinks.

  3. Russ Says:

    Ping. Your wish has been granted.

Leave a Reply