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.

Update 6/24/2013:

This script unfortunately no longer works as Twitter has officially dropped support for APIv1. Not to fear! I will be posting a new tutorial to accommodate the new API as well as CSS/HTML updates soon, check back.

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='ajax-loader.gif' alt='Loading...' />";
	var url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=alovefordesign&include_rts=true&callback=twitterCallback2&count=5';
	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_str+'">'+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 "screen_name" variable to your twitter account.

var url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=alovefordesign&include_rts=true&callback=twitterCallback2&count=5';

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">
    <h1>A Love For Design</h1>
    <h2>Twitter Feed</h2>
    <ul id="twitter_update_list">
    </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;
	position: relative;
	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: 50%; left: 50%; }
#twitter	{ position: relative; width: 280px; background: #222; height: 820px; margin: 50px 0 0 250px;  }
#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	{
	width: 95px;
	height: 23px;
	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;
}
a:link#go_back, a:active#go_back, a:visited#go_back	{
	display: block;
	background: url(/demos/go_back.jpg) no-repeat top left;
	width: 120px;
	height: 40px;
	position: absolute;
	top: 50px;
	left: 100px;
	text-indent: -9999px;
	color: #111;
}
a:hover#go_back {
	background: url(/demos/go_back.jpg) no-repeat -120px 0;
}
</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='ajax-loader.gif' alt='Loading...' />";
	var url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name=alovefordesign&include_rts=true&callback=twitterCallback2&count=5';
	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_str+'">'+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>
	<a id="go_back" href="javascript:history.go(-1)">Go Back</a>
	<div id="twitter">
		<h1>A Love For Design</h1>
		<h2>Twitter Feed</h2>
		<ul id="twitter_update_list">
        </ul>
	</div>
</body>
</html>

, , , , ,



Jun

24

47 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/'+twittersi.id+'&quot; 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/'+twittersi.id+'&quot; 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!

  23. Tabitha
    April 23rd, 2012
    4:55 pm

    How can I display photos on the feed when they are tweeted?

  24. May 7th, 2012
    11:00 pm

    There seems to be an 404 when clicking on the time of the second tweet rendered.

  25. Robert Zeno
    May 8th, 2012
    8:01 am

    Is there a way where you can show the retweets also? Because it is counting them in the count but not showing them so if my count is 6 and I have 1 retweet it only shows 5.

    Thanks,

  26. Megan
    July 5th, 2012
    5:31 am

    Hi, I’m trying to reduce the sizing so that its fits 204px square. I’ve got all of it to work, appart from the the actual text of the tweet, which runs outside of the box. I am trying to find the part which controls the length of the tweet text but can’t seem to change it. Can you help me out?

    Thanks

  27. July 9th, 2012
    9:16 pm

    @Lucas Degen – Thanks for the comment, I went a head and double checked but it seems to be working out fine. Maybe it was a twitter back end problem at the time of your visit?
    @Robert Zeno – The API is about a year and some old and actually didn’t include retweets in their code; as far as I know they have recently added it in newer versions being used. I may do a new one this year as a newer developments have been made since writing this article.
    @Megan – The text of the tweet is simple inline text so you have full control of the css but I would start by checking out the following css from the article:

    #twitter li p  { padding: 0 0 15px; }
    #twitter ul    {
         width: 260px;
         height: auto;
         padding: 15px 0 0 15px;
         margin: 0;
    }
    

    and

    #twitter li    {
         float: left;
         margin: 3px 0;
         list-style-type: none;
    }
    
  28. Bryce
    September 15th, 2012
    5:16 am

    Pretty late to the party here, but a quick question:

    If I want the date to be more “Twittery” (i.e. 5 months ago, or 30 days ago) instead of “March 10, 2012″, what changes do I need to make to the relative_time function?

    Thanks!

  29. October 11th, 2012
    2:30 am

    Hey! thanks for the plugin. Just to let you know your demo and downloads file have stopped working for some reason after much editing to fix it. It worked before and I had it successfully wired into my site about a month ago. Now it stays on the loading gif as of 3 days ago approx. . Not sure if twitter have changed any API’s or theres a defunct javascript method floating around in the script?

  30. October 12th, 2012
    10:04 pm

    Hey Alex,

    Looks like Twitter has updated quite a bit since this tutorial was written. They changed their URLs around so I went ahead and re-uploaded an updated version.

    Thanks!

  31. Jen
    October 14th, 2012
    7:28 am

    Hi, I’m also wondering how to change the date format. How can I make it say 30 days ago, 1 month ago, etc?

  32. October 17th, 2012
    1:24 am

    Nice one dude, thanks for sharing.

  33. November 7th, 2012
    7:08 am

    The date link doesn’t go to the location of the post you clicked on. It takes you to a broken page. Might want to look into that.
    Other than that, superb script! Thanks!

  34. November 7th, 2012
    11:09 pm

    Hey Seth, thanks for pointing that out. Looks like it was the API again. Should be fixed now!

  35. November 21st, 2012
    2:55 am

    This doesn’t work anymore?

  36. Fedora
    November 21st, 2012
    4:19 am

    Hello! I’m having a problem with getting this to work. I change the “screen_name” variable to my twitter account (FedoraGibbles1) but it does not display any of my tweets. When I change it back to “screen_name” it shows the tweets in the demo again. Can you help me please?

  37. Anthony
    November 23rd, 2012
    12:10 pm

    I keep receiving the following error: “Uncaught ReferenceError: twitterCallback2 is not defined ”

    I copied your code and put it in my js file. Also used the same html markup, however it doesn’t seem to work.

    Any ideas?

  38. December 5th, 2012
    7:34 pm

    @Niels, is that a question or statement? Everything works fine on my end.

    @Fedora, if your profile is private it will cause problems, otherwise it should change to any screen name. I just tested with @twitterapi to be sure.

    @Anthony, sounds like your not calling the javascript correctly. Hence why twitterCallback2 isn’t defined.

  39. January 2nd, 2013
    7:02 am

    Hi Justin,

    I’ve almost managed to get your great script working. It loads the feeds and all, but doesn’t recognize the stylesets. This is I believe because I have a stylesheet in a subdirectory called ‘css’, and I’ve put the script into a seperate js-file called twitterfeed, which is also in a subdirectory called ‘js’.

    The folder hierarchy looks something like this:
    index.html
    css/style.css
    js/twitterfeed.js

    Is there an easy fix to make it work in this way?

    Thanks a bunch!

    Wouter

  40. January 2nd, 2013
    1:32 pm

    Hey Wouter, have you tried using a relative path like “../css/style.css”? I know it’s definitely possible, you’ll just have to mess around with the paths to make it work right.

  41. January 23rd, 2013
    12:32 pm

    Hi,

    I’m having trouble with a coming up in my html when I implement this feature. I looked everywhere I could think of and I cannot seem to find where it is coming from. It causes my Tweets to be offset (as if there are bullets there).

    Can someone take a look at what I’ve got and tell me how to resolve it…

    Thanks…

  42. Jess
    January 28th, 2013
    4:22 pm

    When creating the custom feed, which works fine. But when adding it to my blogger site, the twitterfeed css in being over ridden by the main template css.
    I’ve tried embedding the style sheet but no luck.
    Any advise.
    Thank you
    Jess

  43. January 31st, 2013
    11:57 am

    @Dedoceo that sounds to be a default styling for an unordered list. Typically applying

    list-style: none;

    on the list items will fix that problem.

    @Jess if you’re loading the twitter CSS BEFORE the main css it most likely will be overwritten. Try putting it after the main css. If that’s not the problem then you will have to remove whatever is conflicting with the twitter css in the main css. Typically you would look for stylings on the unordered list e.g: ul li { styles }

  44. Original Paulie D
    February 27th, 2013
    8:52 pm

    @Anthony and other getting the “ReferenceError: twitterCallback2 is not defined” error, Twitter put some changes into effect in the last quarter of 2012: https://dev.twitter.com/discussions/11816

    I was able to resolve this, by replacing the jQuery:

    $.getScript(“http://twitter.com/javascripts/blogger.js”)

    with the physical functions in my own code.

  45. Mariah
    June 13th, 2013
    10:09 am

    The twitter feed is not showing up now, when I first implemented it into the site, it was that was about a week ago. I thought maybe it was something with the code I did, however when I opened a new html document and just copied and pasted your original code, your twitter feed isn’t showing up either. Any thoughts on how to fix this or why this is happening?

    Thanks!

  46. SRSS
    June 14th, 2013
    2:40 pm

    The Twitter REST API v1 is no longer active and you have to migrate to API v1.1 https://dev.twitter.com/docs/api/1.1/overview

  47. Johnc834
    August 13th, 2014
    5:50 pm

    Outstanding post, I conceive people should acquire a lot from this web blog its rattling user genial. So much superb info on here efdkdefdbdke