Display Latest Tweets From Twitter Using HTML and JavaScript

Introduction

 
In my last article, I discussed how to display Tweets on your webpage in the easiest way. This article will continue the Twitter series and deal with the situation in which you want to load Tweets of a specific user on the fly or at run time. The focus of this article is to help you when you are planning to implement any or all of the following:
  • Coding a webpage and want to display the Tweets without an IFrame.

  • Auto-Refresh the latest Tweets on the webpage using JavaScript. In case you do not understand how to do this and still do not by the end of this article then feel free to comment or contact me.
Update: From June 11, 2013, onwards, the below method is no more applicable and deprecated by Twitter API. Use this link instead.
 
To get started, let's build the HTML markup first. Place the following tag in your document.
  1. <div id="twitter-feed"></div> 
Once we have the markup ready, it is time to write some piece of JavaScript. Since we will be using jQuery, let's include the reference to the jQuery Library. I am using the one from Google CDN. You are free to use it from your local source repository as well. Copy and Paste the following code into your <head> tag and save the file as an HTML file. Run the file and you'll find the last 10 Tweets from your account (image shows from my account) loaded on the page via JavaScript.
  1. <script src="http:////ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>  
  2. <script type="text/javascript">  
  3.      $(document).ready(function() {  
  4.         loadLatestTweet(10, "niteshluharuka");  
  5.      });  
  6.      String.prototype.parseURL = function() {  
  7.         return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {  
  8.            return url.link(url);  
  9.         });  
  10.      };  
  11.      String.prototype.parseUsername = function() {  
  12.         return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {  
  13.            var username = u.replace("@","")  
  14.            return u.link("http://twitter.com/"+username);  
  15.         });  
  16.      };  
  17.      String.prototype.parseHashtag = function() {  
  18.         return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {  
  19.            var tag = t.replace("#","%23")  
  20.            return t.link("http://search.twitter.com/search?q="+tag);  
  21.         });  
  22.      };  
  23.      function parseDate(str) {  
  24.         var v=str.split(' ');  
  25.         return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));  
  26.      }  
  27.      function loadLatestTweet(numTweets, un){  
  28.         var _url = 'https://api.twitter.com/1/statuses/user_timeline/' + un + '.json?callback=?&count='+numTweets+'&include_rts=1';  
  29.         $.getJSON(_url,function(data){  
  30.            for(var i = 0; i< data.length; i++){  
  31.               var tweet = data[i].text;  
  32.               var created = parseDate(data[i].created_at);  
  33.               var createdDate = created.getDate()+'-'+(created.getMonth()+1)+'-'+created.getFullYear()+' at '+created.getHours()+':'+created.getMinutes();  
  34.               //Uncomment below line to see the user Image  
  35.               //tweet = "<img src='"+data[i].user.profile_image_url+"' />";  
  36.               tweet = tweet.parseURL().parseUsername().parseHashtag();  
  37.               //Uncomment below line to displ tweet date.  
  38.               //tweet += '<div class="tweeter-info"><p class="right">'+createdDate+'</p></div>'  
  39.               $("#twitter-feed").append('<p>'+tweet+'</p>');  
  40.            }  
  41.         });  
  42.     }  
  43. </script> 
In the code above, in line 4 you notice the statement 'loadLatestTweet(10, "niteshluharuka");'.
 
This function requires the 2 parameters:
  • 1st parameter is the number of Tweets you want to load. If you want to load 5 Tweets then pass the value as 5 instead of 10 as I did.
     
  • 2nd parameter is the account name you want to load the Tweets from. So, if your twitter handle is "mytwitterhandle", then pass "mytwitterhandle" in the function and the function will look like the following:
  1. loadLatestTweet(5, "mytwitterhandle"); 
Once you are able to get the Tweets on your page, its time to give some style to your Tweets. Copy and paste the following CSS into your head section:
  1. <style type="text/css">  
  2.     #twitter-feed {width:300px;border:2px solid #CCC;}  
  3.     p {border-bottom:1px dotted #CCC;padding:10px 5px;margin:0px;line-height:21px;}  
  4.     p.right {border:0px none;}  
  5. </style> 
The following is the complete code.
  1. <html>  
  2. <head>  
  3.     <script src="http:////ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>  
  4.     <script type="text/javascript">  
  5.         $(document).ready(function () {  
  6.             loadLatestTweet(5, "mytwitterhandle");  
  7.         });  
  8.         String.prototype.parseURL = function () {  
  9.             return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function (url) {  
  10.                 return url.link(url);  
  11.             });  
  12.         };  
  13.         String.prototype.parseUsername = function () {  
  14.             return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {  
  15.                 var username = u.replace("@""")  
  16.                 return u.link("http://twitter.com/" + username);  
  17.             });  
  18.         };  
  19.         String.prototype.parseHashtag = function () {  
  20.             return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {  
  21.                 var tag = t.replace("#""%23")  
  22.                 return t.link("http://search.twitter.com/search?q=" + tag);  
  23.             });  
  24.         };  
  25.         function parseDate(str) {  
  26.             var v = str.split(' ');  
  27.             return new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC"));  
  28.         }  
  29.         function loadLatestTweet(numTweets, un) {  
  30.             var _url = 'https://api.twitter.com/1/statuses/user_timeline/' + un + '.json?callback=?&count=' + numTweets + '&include_rts=1';  
  31.             $.getJSON(_url, function (data) {  
  32.                 for (var i = 0; i < data.length; i++) {  
  33.                     var tweet = data[i].text;  
  34.                     var created = parseDate(data[i].created_at);  
  35.                     var createdDate = created.getDate() + '-' + (created.getMonth() + 1) + '-' + created.getFullYear() + ' at ' + created.getHours() + ':' + created.getMinutes();  
  36.                     //Uncomment below line to see the user Image  
  37.                     //tweet = "<img src='"+data[i].user.profile_image_url+"' />";  
  38.                     tweet = tweet.parseURL().parseUsername().parseHashtag();  
  39.                     //Uncomment below line to displ tweet date.  
  40.                     //tweet += '<div class="tweeter-info"><p class="right">'+createdDate+'</p></div>'  
  41.                     $("#twitter-feed").append('<p>' + tweet + '</p>');  
  42.                 }  
  43.             });  
  44.         }  
  45.     </script>  
  46.     <style type="text/css">  
  47.         #twitter-feed  
  48.         {  
  49.             width: 300px;  
  50.             border: 2px solid #CCC;  
  51.         }   
  52.         p  
  53.         {  
  54.             border-bottom: 1px dotted #CCC;  
  55.             padding: 10px 5px;  
  56.             margin: 0px;  
  57.             line-height: 21px;  
  58.         }   
  59.         p.right  
  60.         {  
  61.              border: 0px none;  
  62.          }  
  63.     </style>  
  64. </head>  
  65. <body>  
  66. </body>  
  67. <div id="twitter-feed"></div>  
  68. </html> 

Summary

 
Hope you enjoyed reading this article and find this helpful. Comment your experiences and let me know in case you encounter any issues during implementation.


Similar Articles
Rebin Infotech
Think. Innovate. Grow.