Add A Custom Ajax Twitter Feed To Your Web Site

A lot of people like to add a twitter feed to their website for convenience, but many of them are template files that they download and copy/paste onto their website and looks out of place. Twitter has provided an API service to their registered users to use jSON to pull information and display it whichever way the creator likes. In this tutorial I’ll show you how to add a completely custom twitter feed controlling how many tweets, how the date is displayed, and if their linked or not.

Twitter

"Twitter is a real-time information network powered by people all around the world that lets you share and discover what’s happening now." – Twitter.com/about

The following uses Twitters API to pull the correct information wanted and displays as told by JavaScript. While the list is being populated we added a loading ajax image to show that the tweets are being loaded and don’t clog the site from loading everything else. Then is listed in a specific ul classed and dynamically added by the jSON, after all is added we can start adding css to style it how ever we want!

Custom Ajax Twitter Screenshot

Adding the JavaScript

So what this does is it calls the URL below to your twitter account, pulls the information into a .json and then uses the jQuery push command to add HTML to our defined #id. You may edit the HTML that’s being pushed if you know what your doing, otherwise I would keep as is because you could end up breaking the script.

The javascript will find our id (which is called #twitter_update_list) and insert the HTML into the ul, which has the date and the tweet in separate li’s. Right now only the twitter date is wrapped in a link to follow to the actual tweet but we can customize this to how every we want meaning, we can make the whole thing link or remove the link entirely. It’s all up to you…

//Twitter
window.onload = function() {
	var ajax_load = "<img class='loader' src='images/loader.gif' alt='Loading...' />";
	var url = 'http://twitter.com/statuses/user_timeline/username.json?callback=twitterCallback2&amp;count=4';
	var script = document.createElement('script');
	$("#twitter_feed").html(ajax_load);
	script.setAttribute('src', url);
	document.body.appendChild(script);
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g,
	function(url) { return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li class="twitter_date"><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li> <li><p>'+status+'</p></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + " " + values[5] + " " + values[3];
  var parsed_date = new Date();
  parsed_date.setTime(Date.parse(time_value));
  var months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
	'Sep', 'Oct', 'Nov', 'Dec');
  var m = parsed_date.getMonth();
  var postedAt = '';
  postedAt = months[m];
  postedAt += " "+ parsed_date.getDate();
  postedAt += ","
  postedAt += " "+ parsed_date.getFullYear();
  return postedAt;
}

Change the "username" to your twitter account to pull your tweets.

var url = 'http://twitter.com/statuses/user_timeline/username.json?callback=twitterCallback2&count=4';

Adding the HTML

Below we created an unordered list with the id #twitter_update_list which javascript looks for to add the html

<div id="twitter">
      <ul>
           <li id="twitter_feed"></li>
      </ul>
</div>

Adding the CSS

The point of this part is just to show you how dynamic you can get with the styling just because the twitter feed classes all their selectors so it makes for great css editing. This is my quick example of what you can do with this flexable API and jSON, be creative. Go WILD!

body	{
	background: #111111;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 14px;
	font-weight: bold;
	color: #ccc;
}
h1 { padding: 20px 0 0 15px; margin: 0; letter-spacing: -3px; }
h2 { padding: 0 0 0 15px; margin: 0; color: #777; letter-spacing: -2px; }
.loader		{ position: absolute; top: 250px; left: 105px; }
#twitter	{ position: relative; width: 280px; background: #222; height: 820px;  }
#twitter li p	{ padding: 0 0 15px; }
#twitter p a:link, #twitter p a:active, #twitter p a:visited	{ color: #6fb2cd; text-decoration: none; }
#twitter p a:hover	{ text-decoration: underline; }
#twitter ul	{
	width: 260px;
	height: auto;
	padding: 15px 0 0 15px;
	margin: 0;
}
#twitter li	{
	float: left;
	margin: 3px 0;
	list-style-type: none;
}
li.twitter_date	{
	background: url(../images/date_bg.jpg) no-repeat left top;
	width: 95px;
	height: 23px;
	text-align: center;
	line-height: 21px;
}
.twitter_date a:active, .twitter_date a:link, .twitter_date a:visited	{
	color: #666;
	background: #333;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	text-decoration: none;
	text-transform: uppercase;
	padding: 7px;
}
.twitter_date a:hover	{
	color: #666;
}

Final Code

For all the lazies, who don’t want to go through the tutorial and actually read and find out how it works, here’s the final code of my version of a custom twitter feed.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Custom Twitter Feed</title>
<style type="text/css">
body	{
	background: #111111;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 14px;
	font-weight: bold;
	color: #ccc;
}
h1 { padding: 20px 0 0 15px; margin: 0; letter-spacing: -3px; }
h2 { padding: 0 0 0 15px; margin: 0; color: #777; letter-spacing: -2px; }
.loader		{ position: absolute; top: 250px; left: 105px; }
#twitter	{ position: relative; width: 280px; background: #222; height: 820px;  }
#twitter li p	{ padding: 0 0 15px; }
#twitter p a:link, #twitter p a:active, #twitter p a:visited	{ color: #6fb2cd; text-decoration: none; }
#twitter p a:hover	{ text-decoration: underline; }
#twitter ul	{
	width: 260px;
	height: auto;
	padding: 15px 0 0 15px;
	margin: 0;
}
#twitter li	{
	float: left;
	margin: 3px 0;
	list-style-type: none;
}
li.twitter_date	{
	background: url(../images/date_bg.jpg) no-repeat left top;
	width: 95px;
	height: 23px;
	text-align: center;
	line-height: 21px;
}
.twitter_date a:active, .twitter_date a:link, .twitter_date a:visited	{
	color: #666;
	background: #333;
	font-family: Arial, Helvetica, sans-serif;
	font-size: 11px;
	text-decoration: none;
	text-transform: uppercase;
	padding: 7px;
}
.twitter_date a:hover	{
	color: #666;
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
//Twitter
window.onload = function() {
	var ajax_load = "<img class='loader' src=' loader.gif' alt='Loading...' />";
	var url = 'http://twitter.com/statuses/user_timeline/alovefordesign.json?callback=twitterCallback2&count=6';
	var script = document.createElement('script');
	$("#twitter_feed").html(ajax_load);
	script.setAttribute('src', url);
	document.body.appendChild(script);
}

function twitterCallback2(twitters) {
  var statusHTML = [];
  for (var i=0; i<twitters.length; i++){
    var username = twitters[i].user.screen_name;
    var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g,
	function(url) { return '<a href="'+url+'">'+url+'</a>';
    }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
      return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
    });
    statusHTML.push('<li class="twitter_date"><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></li> <li><p>'+status+'</p></li>');
  }
  document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

function relative_time(time_value) {
  var values = time_value.split(" ");
  time_value = values[1] + " " + values[2] + " " + values[5] + " " + values[3];
  var parsed_date = new Date();
  parsed_date.setTime(Date.parse(time_value));
  var months = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
	'Sep', 'Oct', 'Nov', 'Dec');
  var m = parsed_date.getMonth();
  var postedAt = '';
  postedAt = months[m];
  postedAt += " "+ parsed_date.getDate();
  postedAt += ","
  postedAt += " "+ parsed_date.getFullYear();
  return postedAt;
}										 

</script>
</head>
<body>
	<div id="twitter">
		<h1>A Love For Design</h1>
		<h2>Twitter Feed</h2>
		<ul id="twitter_update_list">
        	<li id="twitter_feed"></li>
        </ul>
	</div>
</body>
</html>

, , , , ,



Jun

24

22 Comments made, post one now! We love comments.

  1. Daniel
    October 20th, 2010
    1:47 pm

    Is this up to date?

  2. October 23rd, 2010
    8:04 pm

    Hey Daniel,

    As of June 2010 (When I wrote this tutorial) yes it is up-to-date. If from then to now there has been an even NEWER update then no it’s not.
    - Justin

  3. Tom
    December 31st, 2010
    6:34 pm

    Is there a way to put the date after the tweet? I can’t seem to find how to reorder the elements. Thanks.

  4. January 1st, 2011
    2:54 pm

    Hey Tom,

    There sure is, if you look on line 072 on the final code you can see the following code:

    <li class="twitter_date"> <a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'" rel="nofollow"> '+relative_time(twitters[i].created_at)+' </a> </li>
    <li> <p> '+status+' </p> </li>
    

    Simply place the whole

     <li class="twitter_date"></li> 

    with the link inside after the li with +status+ in it! So it would look like this:

    <li> <p> '+status+' </p> </li>
    <li class="twitter_date"> <a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'" rel="nofollow"> '+relative_time(twitters[i].created_at)+' </a> </li>
    
  5. Tom
    January 6th, 2011
    12:20 am

    You Guys are great :D

  6. Simon
    January 9th, 2011
    1:52 am

    Can I show feeds from more than one user? Thanks/Simon

  7. January 16th, 2011
    1:46 pm

    how do i join

  8. kev
    April 4th, 2011
    2:08 am

    basically the same as twitter offer on their site.

  9. Robbie
    April 28th, 2011
    11:02 am

    How can I limit the number of displayed posts?

  10. April 28th, 2011
    1:00 pm

    Hey Robbie,

    As you can see in the javascript where we’re pulling the .json you can select how many tweets you wante displayed by the count value in the address.

     var url = 'http://twitter.com/statuses/user_timeline/alovefordesign.json?callback=twitterCallback2&count=6'; 
     count=6 

    Change that number to your desired tweet amount.

    Enjoy!

    - Justin Mathew

  11. MachineR
    May 9th, 2011
    3:11 pm

    Thanks a lot man!!!

    Great tutorial =)

  12. May 26th, 2011
    8:26 am

    Thank you for writing this article. I really enjoyed it. I work in web design as well. Keep up the excellent work!

  13. Bobok
    July 21st, 2011
    10:30 am

    Love the script and it works like a dream – thank you.

    One question: Is there any way to display the tweet time after the date?

    Thanks, keep up the great work!

  14. Denise
    August 9th, 2011
    10:30 am

    Love it! Thanks :)

    It’d also be great to have the time. Or even the “time ago”. Is that possible? I didn’t see a response to Bobok. Thanks!

  15. Alex
    August 17th, 2011
    10:39 am

    @Denise and @Bobok there is a tutorial on Youtube that doesn’t use ajax but includes a script to figure out how long ago something was posted then say 2 hours ago or a few mintes ago etc. I can’t figure out how to integrate that though. Hope someone else can :)

  16. Sam
    August 21st, 2011
    6:26 pm

    Thanks for the code, it works great. c:

    I was wondering if there was any way to display the date below the text instead of above?

    thank you c:

  17. Sam
    August 21st, 2011
    11:49 pm

    Oh nevermind, it’s already been answered. Sorry about that, but I do have a real issue of none of the post permalinks actually being correct.

    I don’t know if anyone else is having the same issue, but yeah other than that, it works fine.

  18. September 28th, 2011
    3:56 pm

    Hey, great tutorial!
    Comes in really handy to have references like this.

    Caught a couple snags along the way…not a mood killer, just thought you might want to know.

    the in the first “adding html” snippet is missing its ID…causes confusion if you copy/paste from there

    also, the counts weren’t working for me until I changed the & amp ; into a pure &…

    Thanks for the tutorial!

  19. October 12th, 2011
    5:19 pm

    Worked like a charm, thank you for the awesome information. Subscribed to your site!

    Wes -

  20. Jon
    October 16th, 2011
    11:26 pm

    Great tutorial, cheers Justin.

    Does anyone know if there’s a way to introduce a snippet of code within this that can vet comments and prevent them from displaying?

    e.g. if I didn’t want any comments to appear that contained a swear word, for example.

    Cheers,

    Jon

  21. Miguel
    November 9th, 2011
    11:19 am

    Great post! This worked like a charm, and very helpful. Is there any way to have the time be in relation to normal (4:20pm) and also to add the am/pm pertaining to the hour? That would be helpful. Thanks!

  22. Jade Lester
    January 18th, 2012
    1:05 am

    Hey,

    How can I display how long ago the twitter post was instead of the twitter post date? So like another feed you would see “2 hours ago” or whatever after the status update.

    Thanks!