Tuesday, September 8, 2009

Create a twitter reader using JQuery

  The year of JavaScript has come and JQuery is one of the powerful JavaScript libraries out there. We could perform a multitude of tasks using these libraries. I have created a twitter reader that displays a user's timeline using JQuery. The implementation is very simple.
See the code below.  
 



<html>
<head>
<title>Twitter Reader</title>
<script src="jquery.js" language="javascript"></script>
</head>
<body align="center" bgcolor="#181C21">
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$.getJSON("http://twitter.com/statuses/user_timeline/prasanthkumars.json?callback=?",
function(data){
$.each(data,function(i, item){
$("<div style='color:#865833'>"+item.text+"</div>").appendTo("body");
});
$("div").filter(function(index){
return (index % 2 == 0);
}).css("background","#1FC8FE").css("width","30%");
$("div").filter(function(index){
return (index > 0 && index % 2 != 0);
}).css("background","#CBF2FF").css("width","30%");
});
});
</script>
<div id="twitterResponseDiv" name="twitterResponseDiv" style="font-family:verdana;color:green;background-color:#CBF2FF;width:30%">
Twitter Response Div
</div>
</body>
</html>


I have included the jquery.js file to the page and then used the getJSON method to load JSON data using an HTTP GET request. On receipt of data, it is looped and the text is displayed in different divs which is attached to the body element.

For showing different colors for alternating divs. I have used the filter function available with JQuery.

References :
  1. http://docs.jquery.com/Getjson
  2. http://apiwiki.twitter.com/Twitter-API-Documentation