A jQuery Twitter Ticker
A jQuery Twitter Ticker
Introduction
In this tutorial we are going to create a pure jQuery & CSS twitter ticker which utilizes Twitter’s Search API. It will show your or your friends’ latest tweets, and will not require any server side code or databases. As a result, the ticker will be easily included into any web page and easily modified to your likings.
View The DEMO
Step 1 – XHTML
The XHTML part is quite straightforward.
demo.html
01.<div id="twitter-ticker"> 02.<!-- Twitter container, hidden by CSS and shown if JS is present -->03. 04. <div id="top-bar"> 05. <!-- This contains the title and icon -->06. 07. <div id="twitIcon"><img src="img/twitter_64.png" width="64" height="64" alt="Twitter icon" /></div> 08. <!-- The twitter icon -->09. 10. <h2 class="tut">My tweets</h2> 11. <!-- Title -->12. 13. </div> 14. 15. <div id="tweet-container"><img id="loading" src="img/loading.gif" width="16" height="11" alt="Loading.." /></div> 16. <!-- The loading gif animation - hidden once the tweets are loaded -->17. 18. <div id="scroll"></div> 19. <!-- Container for the tweets -->20. 21.</div>The twitter ticker operates only if JavaScript is present and enabled. That is why we are hiding it in the CSS and showing it with jQuery. This will insure that it is only shown if working properly.
Lets move to the CSS

Step 2 – CSS
This is the place you should start from if you plan to modify the demo.
demo.css
001.body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{ 002. /* Resetting some of the page elements */003. margin:0px; 004. padding:0px; 005.} 006. 007.h2.tut{ 008. /* This is the "MY TWEETS" title */009. color:white; 010. font-family:"Myriad Pro", Arial, Helvetica, sans-serif; 011. font-size:16px; 012. padding:12px 0 0 58px; 013. text-transform:uppercase; 014. 015. /* The CSS3 text-shadow property */016. text-shadow:2px 1px 6px #333; 017.} 018. 019.#twitter-ticker{ 020. /* Styling the ticker */021. width:200px; 022. height:300px; 023. background:url(img/slickbg.png) no-repeat #f5f5f5; 024. color:#666666; 025. display:none; 026. 027. /* Rounded corners */028. -moz-border-radius:10px 10px 6px 6px; 029. -khtml-border-radius: 6px; 030. -webkit-border-radius: 6px; 031. border-radius:6px; 032. 033. text-align:left; 034.} 035. 036.#tweet-container{ 037. /* This is where the tweets are inserted */038. height:230px; 039. width:auto; 040. overflow:hidden; 041.} 042. 043.#twitIcon{ 044. /* Positioning the icon holder absolutely and moving it to the upper-left */045. position:absolute; 046. top:-25px; 047. left:-10px; 048. width:64px; 049. height:64px; 050.} 051. 052.#top-bar{ 053. height:45px; 054. background:url(img/top_bar.png) repeat-x; 055. border-bottom:1px solid white; 056. position:relative; 057. margin-bottom:8px; 058. 059. /* Rounding the top part of the ticker, works only in Firefox unfortunately */060. -moz-border-radius:6px 6px 0 0; 061.} 062. 063..tweet{ 064. /* Affects the tweets */065. padding:5px; 066. margin:0 8px 8px; 067. 068. border:1px solid #F0F0F0; 069. background:url(img/transparent.png); 070. 071. width:auto; 072. overflow:hidden; 073.} 074. 075..tweet .avatar, 076..tweet .user, 077..tweet .time{ 078. float:left; 079.} 080. 081..tweet .time{ 082. text-transform:uppercase; 083. font-size:10px; 084. color:#AAAAAA; 085. white-space:nowrap; 086.} 087. 088..tweet .avatar img{ 089. width:36px; 090. height:36px; 091. border:2px solid #eeeeee; 092. margin:0 5px 5px 0; 093.} 094. 095..tweet .txt{ 096. /* Using the text container to clear the floats */097. clear:both; 098.} 099. 100..tweet .user{ 101. font-weight:bold; 102.} 103. 104.a, a:visited { 105. /* Styling the links */106. color:#00BBFF; 107. text-decoration:none; 108. outline:none; 109.} 110. 111.a:hover{ 112. text-decoration:underline; 113.} 114. 115.#loading{ 116. /* The loading gif animation */117. margin:100px 95px; 118.}And as any experienced front-end developer can assure you, the code is not complete without some special IE6 treatment.
01.<!--[if lt IE 7]> 02. 03.<style type="text/css"> 04.div.tweet { 05. background:none; 06. border:none; 07.} 08. 09.div#twitIcon{ 10. filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=img/twitter_64.png, sizingMethod=crop); 11.} 12. 13.div#twitIcon img{ 14. display:none; 15.} 16. 17.</style> 18.<![endif]-->This will take care of the PNG transparency issues in IE6.
Below you can see a detailed explanation of the twitter ticker.

Now lets take a look at the jQuery source.
Step 3 – jQuery
Being front-end only, the widget takes advantage of the Twitter’s Search API. This a really simple solution for fetching data from the twitter’s infrastructure without the need of any server-side code or databases.
Here is how it works:
- The ticker loads;
- JS builds the twitter search api URL from the provided twitter usernames (in the tweetUsers array) and a name of a callback function (TweetTick in our case);
- It includes a script file in the page, using the above URL as its src;
- The script in turn calls the callback function and provides a special object containing all the tweets as a parameter;
- The callback function uses this object to build and show the tweets;
As the search api script is called after page load, there is no waiting for the script to load and hanging of the page in the mean time. This is a true asynchronous javascript solution – a great alternative to AJAX.
Now here is the code that makes this happen:
demo.html
1.<link rel="stylesheet" type="text/css" href="demo.css" /> 2.<link rel="stylesheet" type="text/css" href="jScrollPane/jScrollPane.css" /> 3. 4.<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 5.<script type="text/javascript" src="jScrollPane/jquery.mousewheel.js"></script> 6.<script type="text/javascript" src="jScrollPane/jScrollPane-1.2.3.min.js"></script> 7.<script type="text/javascript" src="script.js"></script>First, we include our demo.css and jScrollPane.css. These style the ticker.
Later we include the jQuery library from Google’s CDN, the mousewheel plugin and the jScrollPane plugin.
Last is script.js, which is shown below:
script.js
001.var tweetUsers = [´tutorialzine´,´TechCrunch´, 002.´smashingmag´,´mashable´]; 003.// The twitter accounts that will be included in the ticker 004. 005.var buildString = ""; 006. 007.$(document).ready(function(){ 008. 009. // After the page is loaded 010. 011. $(´#twitter-ticker´).slideDown(´slow´); 012. // Show the ticker 013. 014. for(var i=0;i<tweetUsers.length;i++) 015. { 016. // Build the search api parameters 017. if(i!=0) buildString+=´+OR+´; 018. buildString+=´from:´+tweetUsers[i]; 019. } 020. 021. var fileref = document.createElement(´script´); 022. // Creating a new script element 023. 024. fileref.setAttribute("type","text/javascript"); 025. fileref.setAttribute("src", "http://search.twitter.com/search.json?q="+buildString+"&callback=TweetTick&rpp=50"); 026. // Setting its src to the search API URL; We provide TweetTick as a callback 027. 028. document.getElementsByTagName("head")[0].appendChild(fileref); 029. // Appending it to the head of the page and thus executing it 030.}); 031. 032.function TweetTick(ob) 033.{ 034. // This is the callback function 035. 036. var container=$(´#tweet-container´); 037. container.html(´´); 038. // Removing the loading gif animation 039. 040. $(ob.results).each(function(el){ 041. 042. // ob contains all the tweets 043. 044. var str = ´ <div class="tweet">\ 045. <div class="avatar"><a href="http://twitter.com/´+this.from_user+´" target="_blank"><img src="´+this.profile_image_url+´" alt="´+this.from_user+´" /></a></div>\ 046. <div class="user"><a href="http://twitter.com/´+this.from_user+´" target="_blank">´+this.from_user+´</a></div>\ 047. <div class="time">´+relativeTime(this.created_at)+´</div>\ 048. <div class="txt">´+formatTwitString(this.text)+´</div>\ 049. </div>´; 050. 051. container.append(str); 052. // Adding the tweet to the container 053. }); 054. 055. container.jScrollPane(); 056. // After all the tweets have been added, create the slidebar 057.} 058. 059.function formatTwitString(str) 060.{ 061. // This function formats the tweet body text 062. 063. str=´ ´+str; 064. 065. str = str.replace(/((ftp|https?):\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?)/gm,´<a href="$1" target="_blank">$1</a>´); 066. // The tweets arrive as plain text, so we replace all the textual URLs with hyperlinks 067. 068. str = str.replace(/([^\w])\@([\w\-]+)/gm,´$1@<a href="http://twitter.com/$2" target="_blank">$2</a>´); 069. // Replace the mentions 070. 071. str = str.replace(/([^\w])\#([\w\-]+)/gm,´$1<a href="http://twitter.com/search?q=%23$2" target="_blank">#$2</a>´); 072. // Replace the hashtags 073. 074. return str; 075.} 076. 077.function relativeTime(pastTime) 078.{ 079. // Generate a JavaScript relative time for the tweets 080. 081. var origStamp = Date.parse(pastTime); 082. var curDate = new Date(); 083. var currentStamp = curDate.getTime(); 084. var difference = parseInt((currentStamp - origStamp)/1000); 085. 086. if(difference < 0) return false; 087. 088. if(difference <= 5) return "Just now"; 089. if(difference <= 20) return "Seconds ago"; 090. if(difference <= 60) return "A minute ago"; 091. if(difference < 3600) return parseInt(difference/60)+" minutes ago"; 092. if(difference <= 1.5*3600) return "One hour ago"; 093. if(difference < 23.5*3600) return Math.round(difference/3600)+" hours ago"; 094. if(difference < 1.5*24*3600) return "One day ago"; 095. 096. // If the tweet is older than a day, show an absolute date/time value; 097. 098. var dateArr = pastTime.split(´ ´); 099. 100. return dateArr[4].replace(/\:\d+$/,´´)+´ ´+dateArr[2]+´ ´+dateArr[1]+ 101. (dateArr[3]!=curDate.getFullYear()?´ ´+dateArr[3]:´´); 102.}You can see that on line 55 we use the jScrollPane plugin. It creates a handy scrollbar to the right of the tweets. Thanks to the mouseWheel plugin it is also able to detect and scroll the page on mouse wheel movements.
To change the twitter accounts that are shown in the ticker, you’ll need to modify the tweetUsers array.
If you provide two or more twitter names, their tweets will be shown together. Only the 50 most recent tweets from the past 7 days will be returned.
It is worth noting that Twitter puts a maximum limit to the search api’s URLs of 140 characters. This would be sufficient for about 7 twitter user names.
With this the twitter ticker is complete!

22 January 2010 Friday




