Display Latest Tweets From Twitter Using HTML and JavaScript

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.

<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 a 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.

<script src="http:////ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<
script type="text/javascript">
     $(document).ready(function() {
        loadLatestTweet(10,
"niteshluharuka");
     });
     String.prototype.parseURL =
function() {
       
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function(url) {
           return url.link(url);
        });
     };
     String.prototype.parseUsername =
function() {
       
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
           var username = u.replace("@","")
          
return u.link("http://twitter.com/"+username);
        });
     };
     String.prototype.parseHashtag =
function() {
       
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
           var tag = t.replace("#","%23")
          
return t.link("http://search.twitter.com/search?q="+tag);
        });
     };
    
function parseDate(str) {
       
var v=str.split(' ');
       
return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
     }
    
function loadLatestTweet(numTweets, un){
       
var _url = 'https://api.twitter.com/1/statuses/user_timeline/' + un + '.json?callback=?&count='+numTweets+'&include_rts=1';
        $.getJSON(_url,
function(data){
           for(var i = 0; i< data.length; i++){
             
var tweet = data[i].text;
             
var created = parseDate(data[i].created_at);
             
var createdDate = created.getDate()+'-'+(created.getMonth()+1)+'-'+created.getFullYear()+' at '+created.getHours()+':'+created.getMinutes();
             
//Uncomment below line to see the user Image
              //tweet = "<img src='"+data[i].user.profile_image_url+"' />";
              tweet = tweet.parseURL().parseUsername().parseHashtag();
              
//Uncomment below line to displ tweet date.
              //tweet += '<div class="tweeter-info"><p class="right">'+createdDate+'</p></div>'
              $("#twitter-feed").append('<p>'+tweet+'</p>');
           }

        });
    }
</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:

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:

<style type="text/css">
    #twitter-feed {width:300px;border:2px solid #CCC;}
   
p {border-bottom:1px dotted #CCC;padding:10px 5px;margin:0px;line-height:21px;}
   
p.right {border:0px none;}
</style>

The following is the complete code.

<html>
<
head>
    <script src="http:////ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            loadLatestTweet(5,
"mytwitterhandle");
        });
        String.prototype.parseURL =
function () {
           
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&~\?\/.=]+/g, function (url) {
               
return url.link(url);
            });
        };
        String.prototype.parseUsername =
function () {
           
return this.replace(/[@]+[A-Za-z0-9-_]+/g, function (u) {
               
var username = u.replace("@", "")
               
return u.link("http://twitter.com/" + username);
            });
        };
        String.prototype.parseHashtag =
function () {
           
return this.replace(/[#]+[A-Za-z0-9-_]+/g, function (t) {
               
var tag = t.replace("#", "%23")
               
return t.link("http://search.twitter.com/search?q=" + tag);
            });
        };
       
function parseDate(str) {
           
var v = str.split(' ');
           
return new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC"));
        }
       
function loadLatestTweet(numTweets, un) {
            
var _url = 'https://api.twitter.com/1/statuses/user_timeline/' + un + '.json?callback=?&count=' + numTweets + '&include_rts=1';
            $.getJSON(_url,
function (data) {
               
for (var i = 0; i < data.length; i++) {
                   
var tweet = data[i].text;
                   
var created = parseDate(data[i].created_at);
                   
var createdDate = created.getDate() + '-' + (created.getMonth() + 1) + '-' + created.getFullYear() + ' at ' + created.getHours() + ':' + created.getMinutes();
                   
//Uncomment below line to see the user Image
                    //tweet = "<img src='"+data[i].user.profile_image_url+"' />";
                    tweet = tweet.parseURL().parseUsername().parseHashtag();
                   
//Uncomment below line to displ tweet date.
                    //tweet += '<div class="tweeter-info"><p class="right">'+createdDate+'</p></div>'
                    $("#twitter-feed").append('<p>' + tweet + '</p>');
                }
            });
        }
   
</script>
    <style type="text/css">
        #twitter-feed
        {
           
width: 300px;
           
border: 2px solid #CCC;
        } 
       
p
        {
           
border-bottom: 1px dotted #CCC;
           
padding: 10px 5px;
           
margin: 0px;
           
line-height: 21px;
        } 
        
p.right
        {
            
border: 0px none;
         }
   
</style>
</
head>
<
body>
</
body>
<
div id="twitter-feed"></div>
</
html>

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.

Up Next
    Ebook Download
    View all
    Learn
    View all
    Think. Innovate. Grow.