<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Twitter API and jQuery Exampe</title> <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script> <script type="text/javascript"> // When the document is loaded (jQuery function) $(document).ready(function() { // Call the Twitter API to retrieve the last 10 tweets in JSON format for the pcpro Twitter account $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=pcpro&count=10&callback=?", function(tweetdata) { // Grab a reference to the ul element which will display the tweets var tl = $("#tweet-list"); // For each item returned in tweetdata $.each(tweetdata, function(i,tweet) { // Append the info in li tags to the ul, converting any links to HTML <a href=.. code and convert the tweeted date // to a more readable Twitter format tl.append("<li>&ldquo;" + urlToLink(tweet.text) + "&rdquo;&ndash; " + relTime(tweet.created_at) + "</li>"); }); }); }); // Converts any links in text to their HTML <a href=""> equivalent function urlToLink(text) { var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig; return text.replace(exp,"<a href='$1'>$1</a>"); } // Takes a time value and converts it to "from now" and then returns a relevant text interpretation of it function relTime(time_value) { time_value = time_value.replace(/(\+[0-9]{4}\s)/ig,""); var parsed_date = Date.parse(time_value); var relative_to = (arguments.length > 1) ? arguments[1] : new Date(); var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000); if (timeago < 60) return 'less than a minute ago'; else if(timeago < 120) return 'about a minute ago'; else if(timeago < (45*60)) return (parseInt(timeago / 60)).toString() + ' minutes ago'; else if(timeago < (90*60)) return 'about an hour ago'; else if(timeago < (24*60*60)) return 'about ' + (parseInt(timeago / 3600)).toString() + ' hours ago'; else if(timeago < (48*60*60)) return '1 day ago'; else return (parseInt(timeago / 86400)).toString() + ' days ago'; } </script> </head> <body> <h1>Twitter API example</h1> <p>The following list contains the last 10 tweets from <a href="http://twitter.com/pcpro">PC Pro</a>.</p> <ul id="tweet-list"></ul> </body> </html>