Monday, November 19, 2007

Pulling twitter updates with JSON and jQuery

I wrote a little script tonight to pull in my latest 3 tweets from twitter and display them on my blog.  You can see it in action on the right.

Here is how I did it.  I used the Twitter's API and called my timeline with a JSON call and comsummed it with jQuery and outputted it to a blank div.

       var url = "http://twitter.com/status/user_timeline/RedWolves.json?count=3&callback=?";        $.getJSON(url,         function(data){             $.each(data, function(i, item) {                 $("img#profile").attr("src", item.user["profile_image_url"]);                 $("#tweets ul").append("<li>"                       + item.text.linkify()                       + " <span class='created_at'>"                       + relative_time(item.created_at)                       + " via "                       + item.source                       + "</span></li>");             });         });

Basically what this does is pulls in the data from twitter and makes them available as objects.  I then loop through each item and pull out the data I want and write it out to a unordered list. Update: make sure to look at the complete working example below as it has the two functions this code block is using (linkify and relative_time) to transform the JSON data into how I'd like it to look.

Here is the HTML stub it's going to:

   <div id="tweets">         <img id="profile">         <ul></ul>     </div>

You can download a working example here: twitter-json-jquery.html (1.79 KB)

Saturday, June 07, 2008 5:17:15 PM (Eastern Daylight Time, UTC-04:00)
Found out that dooce.com is using the above twitter/jQuery code. The Announcement.

Is anyone else using this code on their website? if so drop me the link.
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u)  

Enter the code shown (prevents robots):

Blog Posts by:

Currently Viewable:

My Twitter Updates

View Twitter Page