Create A Dead Simple Twitter Feed with jQuery

Introduction

In this tutorial, we will be creating a jQuery script that retrieve twitter tweets from user account. It's quick and easy, come with link, hash tag, alias parser as well as time posted (calculated relatively). Most importantly, everything has a class and will be flexible to style and match your design!

UPDATE #1: If you want to know how to get image attached to a tweet from media entities, visit our new tutorial: Create a Twitter Feed with Attached Images from Media Entities

UPDATE #2: I forgot to mention one thing! Twitter has rate limits. You can only call this API 150 times per hour per IP. The best way to solve this is using cache. So, instead of calling the API in $.ajax call, you get it from your server. A PHP is scheduled (a href="http://adminschoice.com/crontab-quick-reference">CRON Job to retrieve updated twitter feed in certain time and create the cache file once it's loaded. Don't worry, nettuts just released a tutorial about it :) How to Create An Advanced Twitter Widget

UPDATE #3: Alright guys, due to popular demand, I have made a revisit to this tutorial to add hash tag capability! It will support both username and hash tag and most importantly, it has caching function as by using PHP to avoid Twitter Rate Limits. Visit this tutorial: Create a Twitter Feed With Hash Tag And Cache Support

Demo Download

We going to use:

  • Twitter API - user_timeline in JSON format
  • jQuery framework
  • links/hashtag/alias function and time/date function (from twitter widget.js)

HTML

We need a simple HTML layout, linked with jQuery framework and twitter script. Also, a div with id called "jstwitter" - we will be appending all tweets from twitter server, processed it and chuck it inside.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
	<title></title>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
	<script src="twitter.js"></script>
</head>
<body>
	
	<div id="jstwitter">
	</div>
	
</body>
</html>

CSS

We made a quick and clean layout. However, you can style the following elements:

  • .twtr-hashtag: #abc
  • .twtr-hyperlink: hyperlink
  • .twtr-atreply: #abc
  • .time: relative time (10 minutes ago)
#jstwitter {
	width: 300px;
	font-family: georgia;
	font-size: 15px;
	color: #333333;
	padding: 10px;
}

#jstwitter .tweet {
	margin: 0 auto 15px auto;
	padding: 0 0 15px 0;
	border-bottom: 1px dotted #ccc;
}

#jstwitter .tweet a {
	text-decoration: none;
	color: #13c9d0;
}

#jstwitter .tweet a:hover {
	text-decoration: underline;
}

#jstwitter .tweet .time {
	font-size: 10px;
	font-style: italic;
	color: #666666;
}

Javascript

Alright, javascript. We will divide it into 3 sections:

  • loadTweets: This is how we retrieve tweets. We use AJAX to call twitter API in JSON format and then process it.
  • timeAgo: Relative calculator from twitter.
  • ify: Convert twitter hashtag, alias, and links into hyperlinks.
JQTWEET = {
	
	// Set twitter username, number of tweets & id/class to append tweets
	user: 'quenesswebblog',
	numTweets: 5,
	appendTo: '#jstwitter',

	// core function of jqtweet
	loadTweets: function() {
		$.ajax({
			url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
			type: 'GET',
			dataType: 'jsonp',
			data: {
				screen_name: JQTWEET.user,
				include_rts: true,
				count: JQTWEET.numTweets,
				include_entities: true
			},
			success: function(data, textStatus, xhr) {

				 var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>';
		
				 // append tweets into page
				 for (var i = 0; i < data.length; i++) {
					$(JQTWEET.appendTo).append(
						html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text) )
							.replace(/USER/g, data[i].user.screen_name)
							.replace('AGO', JQTWEET.timeAgo(data[i].created_at) )
							.replace(/ID/g, data[i].id_str)
					);
				 }					
			}	

		});
		
	}, 
	
		
	/**
      * relative time calculator FROM TWITTER
      * @param {string} twitter date string returned from Twitter API
      * @return {string} relative time like "2 minutes ago"
      */
    timeAgo: function(dateString) {
		var rightNow = new Date();
		var then = new Date(dateString);
		
		if ($.browser.msie) {
			// IE can't parse these crazy Ruby dates
			then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
		}

		var diff = rightNow - then;

		var second = 1000,
		minute = second * 60,
		hour = minute * 60,
		day = hour * 24,
		week = day * 7;

		if (isNaN(diff) || diff < 0) {
			return ""; // return blank string if unknown
		}

		if (diff < second * 2) {
			// within 2 seconds
			return "right now";
		}

		if (diff < minute) {
			return Math.floor(diff / second) + " seconds ago";
		}

		if (diff < minute * 2) {
			return "about 1 minute ago";
		}

		if (diff < hour) {
			return Math.floor(diff / minute) + " minutes ago";
		}

		if (diff < hour * 2) {
			return "about 1 hour ago";
		}

		if (diff < day) {
			return  Math.floor(diff / hour) + " hours ago";
		}

		if (diff > day && diff < day * 2) {
			return "yesterday";
		}

		if (diff < day * 365) {
			return Math.floor(diff / day) + " days ago";
		}

		else {
			return "over a year ago";
		}
	}, // timeAgo()
    
	
    /**
      * The Twitalinkahashifyer!
      * http://www.dustindiaz.com/basement/ify.html
      * Eg:
      * ify.clean('your tweet text');
      */
    ify:  {
      link: function(tweet) {
        return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
          var http = m2.match(/w/) ? 'http://' : '';
          return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
        });
      },

      at: function(tweet) {
        return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">@' + username + '</a>';
        });
      },

      list: function(tweet) {
        return tweet.replace(/\B[@@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
          return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">@' + userlist + '</a>';
        });
      },

      hash: function(tweet) {
        return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
          return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
        });
      },

      clean: function(tweet) {
        return this.hash(this.at(this.list(this.link(tweet))));
      }
    } // ify

	
};



$(document).ready(function () {
    // start jqtweet!
    JQTWEET.loadTweets();
});

Conclusion

No doubt, twitter is one of the hottest social media, so I hope this tutorial will able to help you to display your own tweets in your website. If you like it, please help me to spread it :) Thanks!

Show Some Love, Spread This Post!

42 comments

Matt Mon, 23rd April 2012 Brilliant! Thank you so much :D
Reply
Hazar Askari Wed, 28th March 2012 Hi Kevin. this is super great :) Im having the same problems as Ryan, sometimes my Tweets doesnt load, i understand its a limitation of the API, but is there any ways to work around this?
Reply
Kevin Liew Wed, 28th March 2012 I did fix the problem in my second tutorial:
http://www.queness.com/post/10778/create-a-twitter-feed-with-hash-tag-and-cache-support
Stefano Fri, 23rd March 2012 Hi,

I got a question. I want to display the tweets of the people that i added to a list on twitter. is this possible
Reply
Michael Budden Thu, 22nd March 2012 Hi Kevin, First of all I wanna say this is a really great tutorial! I am wanting to use this on my site where, within different sections I want to display the latest tweet of a different user. Obviously I can set numTweets to 1 to get the latest tweet, but is there any way to support multiple users?

Thanks in advance, Michael
Reply
Kevin Liew Sun, 25th March 2012 I think it's possible, but you need this tutorial:
http://www.queness.com/post/10778/create-a-twitter-feed-with-hash-tag-and-cache-support

hashtag uses twitter search api, if you used "from" and "OR" operator, you will able to get the tweet from different users:
http://stackoverflow.com/questions/2692434/php-twitter-api-how-to-pull-in-multiple-users-tweets
Willers Wed, 21st March 2012 Cracking tutorial/share!!! This was uber satisfyingly useful!! Ta!!
Reply
XeL Tue, 20th March 2012 The value of attribute "src" associated with an element type "null" must not contain the '<' character.
Reply
Christopher Wed, 14th March 2012 Man u make it look like UNo wish I new how2 apply it()
Reply
ritvik Thu, 8th March 2012 great tutorial but have a question
What if i would like to pass multiple hash tags ?
Reply
Kevin Liew Wed, 21st March 2012 For multiple hashtags, visit this tutorial:
http://www.queness.com/post/10778/create-a-twitter-feed-with-hash-tag-and-cache-support
Tom King Wed, 7th March 2012 Is there a way to externally use the css? I've tried linking it to the html, but no formatting is applied
Reply
Kevin Liew Wed, 7th March 2012 Of course. You need to create a CSS file, and paste the CSS section (content in between<style> </style>).

Then reference the file with this HTML tag:
<link rel="stylesheet" href="css_file_put_here.css" />
ganesh Fri, 24th February 2012 Hi,

Thanks for such simple and great tool, and also thanks to Luke Smith for raising the question to add user name in html file. It worked in a shot for me.
Well is it possible for me to show user's avatar alongwith there tweets, please tell me where should I make changes to get this done, I am unware with jscript, so please give example code.

Thanks
Reply
Kevin Liew Sun, 26th February 2012 I haven't tested it, it should be something like this:


var html = '<div class="tweet"><img src="IMG_URL"><p>TWEET_TEXT</p><div class="time">AGO</div>';

// append tweets into page
for (var i = 0; i < data.length; i++) {
$(JQTWEET.appendTo).append(
html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text) )
.replace(/IMG_URL/g, data[i].user.profile_image_url)
.replace(/USER/g, data[i].user.screen_name)
.replace('AGO', JQTWEET.timeAgo(data[i].created_at) )
.replace(/ID/g, data[i].id_str)
);
}
Jackson Fri, 24th February 2012 Awesome little project. Thanks for sharing!

Do you know how to pull in all the posts (from everyone you follow)? I've been hunting for a way to do this. Apps like Flipboard and others do this, but I can't figure it out.

My goal is to scrape my twitter feed (or rather, a feed containing all the posts of the people I subscribe to) and pull out all the links. I follow a lot of brilliant people, and I love reading their links in my downtime... and Flipboard works well for this, but I want to be able to do it on my own computer... or rather, from a browser, and ultimately archive the links for future reference.

Thoughts?
Reply
Luke Smith Fri, 10th February 2012 This is great! Is there a way I can specify the username in the actual html document? Something like this in the head section:

$(document).ready(function () {
// start jqtweet!
JQTWEET.loadTweets({ user: 'lukediv' });
});

How would I do this?

Reply
Kevin Liew Sun, 12th February 2012 You got me there, but you can do this:

remove this line from the main code: user: 'quenesswebblog',

Then, you can call the function like this:
$(document).ready(function () {
JQTWEET.user = 'quenesswebblog';
JQTWEET.loadTweets();
});
Robert Tue, 31st January 2012 Thanks for this
Reply
shawn Mon, 16th January 2012 awesome work, been searching for this all over, thank you!
Reply
Callum Sun, 8th January 2012 This is fantastic! Thanks. It would be great to also add the avatar and username to the feed. I'm guessing it would be a case of adding a few lines of code to the core function of jqtweet but I'm afraid my java skills are not up to the task. Any idea how to do this?
Reply
Danny Sun, 8th January 2012 Thanks. As a learning exercise I was looking for simple way to handle twitter api with jQuery ajax call, found it all here. Nice and to the point.
Reply
Mike Ilz Tue, 3rd January 2012 Great Twitter feed! Is this ok to use on WordPress themes for resale?.. (just wanted to ask to be safe)
Reply
Kevin Liew Tue, 3rd January 2012 Feel free to use it in any way you want :)
Timothy Wed, 28th December 2011 Thanks for the code!

I was wondering if you can also load #something instead of a user?
Reply
Kevin Liew Mon, 2nd January 2012 it's possible. You have to modify the code and adapt to the hashtag json data. This is how you get the hashtag:

http://search.twitter.com/search.json?q=%23jquery

%23jquery = #jquery
Brandon Wed, 25th January 2012 can you show what this code would look like for the hashtag following?
Kevin Liew Mon, 20th February 2012 Here you go :)

http://www.queness.com/post/10778/create-a-twitter-feed-with-hash-tag-and-cache-support
Meisha Thu, 27th October 2011 Is there a way to get this to work in Opera by any chance? That is the only browser I cannot get it to show up in.
Reply
Kevin Liew Sun, 30th October 2011 Same as previous comment, what you have to do is, in twitter.js change this line (bottom):

// start jqtweet!
JQTWEET.loadTweets();

to

$(document).ready(function () {
// start jqtweet!
JQTWEET.loadTweets();
});
Bicho Malvado Thu, 27th October 2011 Very nice tut, i'm using this in my site, but i doesn't seem to work in Opera :S ....is there a way to make it work?

Cheers
Reply
Kevin Liew Sun, 30th October 2011 Hi Sorry for late reply, it's fixed. What you have to do is, in twitter.js change this line (bottom):

// start jqtweet!
JQTWEET.loadTweets();

to

$(document).ready(function () {
// start jqtweet!
JQTWEET.loadTweets();
});

Leave a comment

Have something to say? Drop a comment! No HTML tags are allowed in the comment textfield.

Advertisement