Display Latest Tweets From A Twitter Account Using HTML & Javascript

March 16th, 2013 | Posted by Nitesh in HTML | Javascript | Twitter

Friends,

In my last post I discussed about how to display tweets on your webpage in the most easiest way. This post will continue the Twitter series and deal with the situation when you want to load tweets of a specific user on the fly or at run time. The focus of this post is to help you when you are planning to implement any one of the following or all things-

  • Coding a webpage and want to display the tweets without and IFrame.
  • Auto Refresh the latest tweets on the webpage using Javascript. In case you do not understadn by the end of this post how you can do this, feel free to comment or contact me :)

Update: Twitter has deprecated v1.0 API since today (12th June 2013) and the below code will not show any tweets to you.
To get started, lets build the HTML markup first. Place the below tag in your tag.

<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, lets include the reference to 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 below code in your <head> tag and save the file as 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 above code, in line 4 you notice the statement ‘loadLatestTweet(10, “niteshluharuka”);’.
This function requires 2 parameters –

  • 1st parameter is the number of tweets you want to load. If you want to load 5 tweets, pass the value as 5 instead of 10 as passed by me.
  • 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 below-
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 below CSS in 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>

Below 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(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>
<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 post and find this helpful. Comment your experiences and let me know in case you face any issues while implementation.

You can follow any responses to this entry through the RSS 2.0 You can leave a response, or trackback.

  • http://sublimewebdesign.com toby

    hi
    I cant seem to get it to work. It works fine as you show – put everything in the head. But I would like to put the js in an external file. how do I change the code to make it work like this?

    Thanks
    Toby

    • http://www.niteshluharuka.com Nitesh

      Toby, You can put all JS scripts in a separate file. I have created a sample for you. You can download it from here.

  • Robert

    Thank you so much for this! I’ve spent hours looking for a good method for this.

  • daVinci

    Hello Nitesh,

    Although it seems that not everything is working properly. My photo is not displayed correctly. Besides, the script adds some more pictures at the end of the entry. How to remove it?

    I also have another question. How to display items in a list, in order to begin with the tag [ul] here the list of tweets – and end it with tag [/ ul]

    Thank You for sharing your work.
    Best wishes
    Daniel M

    • http://www.niteshluharuka.com Nitesh

      Hello Daniel,

      Please use the below function to display images and tweets using ul and li tags. Hope it helps!

      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
      			tweetI = "<img src='"+data[i].user.profile_image_url+"' />";
      			tweetD = 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('<li>'+tweetI+tweetD+'</li>');
              }
          });
      }

      And change your HTML like below–

      <body>
      	<p>Here are your tweets</p>
      	<ul id="twitter-feed"></ul>
      </body>
  • Bryan

    This is now a deprecated method and will not work. Twitter has pulled support for the 1.0 API.

    • http://www.niteshluharuka.com Nitesh

      Agreed Bryan. Have updated the article. :)

  • Reader

    This Code is not working..Not loading tweets…

Support us!

If you like this site please help and make click on any of these buttons!

×