Create A Dead Simple Twitter Feed with jQuery

Create A Dead Simple Twitter Feed with jQuery


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: We have written an updated version of Twitter API tutorial based on Twitter Newest API 1.1. - Easiest Way to Retrieve Twitter Timeline and Hashtags

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!

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

130 comments

nilanjan
Fri, 17th May 2013
Don't you need to follow twitter guidelines to display tweets? I think the guidelines are quite detailed. Not sure..... Reply
Thomas
Sat, 25th May 2013
How would you modify this to display hashtags? Reply
Veera
Tue, 11th June 2013
This method works no longer... API v1.0 died. Please update the post, so that we will know what is the solution. Reply
kalyan
Wed, 12th June 2013
Hay,

This is not working. API 1.1 requires authentication. But you didn't mention that any where! Reply
Kevin Admin
Fri, 14th June 2013
Hi Kalyan, we did mention it. Please check the top part of this article. Reply
Dom
Thu, 13th June 2013
My twitter feed has dropped out. I think it is because I am using a fader from Simon Battersby also running jQuery. http://www.simonbattersby.com/blog/simple-jquery-image-crossfade/

Could you advice which jQuery to run to get both of these to run? Reply
Kevin Admin
Fri, 14th June 2013
I think it's caused by twitter updated its API. You need OAuth authentication to use it now.

Here is the updated tutorial.
http://www.queness.com/post/14004/easiest-way-to-retrieve-twitter-timeline-and-hashtags-twitter-oauth-api-11 Reply
Fabio
Thu, 13th June 2013
Now the script in my site not work... why ?
Also your demo not work.... Reply
Thomas Cober
Tue, 18th June 2013
I was using this one because it didn't involve any server side stuff, but twitter's new API has rendered it pretty useless. Is there any easy fix? Reply
Kevin Admin
Wed, 19th June 2013
You need this new article: http://bit.ly/WABOn9 Reply
Thomas Cober
Sat, 29th June 2013
Is there a way to do it without server side stuff? Reply
Kevin Admin
Sun, 30th June 2013
Unfortunately with OAuth, it has to be done through server-side language. Reply
vincent
Sun, 15th September 2013
not working!!!! Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement