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