Build a jQuery Twitter Feed

Copy and paste the code below into a post, page, widget, or your HTML code. Be sure to replace the screen_name on line 4.

<div class="twitter" id="jstweets"></div>
<script>
$.ajax({
  url: 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=jolamar&count=5&callback=?',
  dataType: 'json',
  success: function(data){
    $.each(data, function(i,item){
      ct = item.text;
      // include time tweeted - thanks to will
      mytime = item.created_at;
      var strtime = mytime.replace(/(\+\S+) (.*)/, '$2 $1')
      var mydate = new Date(Date.parse(strtime)).toLocaleDateString();
      var mytime = new Date(Date.parse(strtime)).toLocaleTimeString();
      ct = ct.replace(/http:\/\/\S+/g,  '<a href="$&" target="_blank">$&</a>');
      twitterURL = "http://twitter.com/";
      ct = ct.replace(/\s(@)(\w+)/g,    ' @<a href="'+twitterURL+'$2">$2</a>');
      ct = ct.replace(/\s(#)(\w+)/g,    ' #<a href="'+twitterURL+'search?q=%23$2" target="_blank">$2</a>');
      $("#jstweets").append('<div>'+ct + ' <small><i>(' + mydate + ' @ ' + mytime + ')</i></small></div>');
    });
  }
});
</script>

NOTE: You will need jQuery for this to work. If this isn’t working, try including the following library at the beginning of this code.

<script src="http://code.jquery.com/jquery-latest.js"></script>

3 comments

  1. Justin says:

    Thanks for this! Got he headed in the right direction. Only thing I noticed was if a tweet starts with a twitter name then it doesn’t provide a link to that user. I added this line:
    ct = ct.replace(/^(@)(\w+)/g, ‘ @$2‘);

    Thanks again.

  2. Wonchan says:

    Thanks heaps. It works great!

    There’s only one thing I’d like to ask;
    How do you specifically modify details such as name, id, date, time, etc?
    For instance, I want to italicise the date, make the date bold, and such.
    Your answer could be mucho appreciated!

    Cheers

Leave a Reply

Your email address will not be published. Required fields are marked *