Themeforest

jQuery Tutorial – Create A jQuery Twitter Feed Plugin

jQuery Twitter Feed Plugin Tutorial

In the following tutorial we are going to go show how to create a jQuery plugin to display Twitter feeds via AJAX from either a username or search using the Twitter API.

The plugin will also include code to display time since posted, retweet, reply & favourite links plus options to set the number of feed items to display, turn on/off retweets and replies, show the user’s avatar and also include any embedded images.

View jQuery Twitter Feed Plugin DemoDownload Demo Source Files

The Twitter Feed Plugin Options

To make the plugin more versatile we are going to include several options, which you can use to customise the output:

  • id – this is where the username or search term will be added when initialising the plugin
  • retweets – option to include/exclude retweets
  • replies – option to include/exclude replies
  • avatar – option to include the tweet author’s avatar
  • results – set the number of results to display
  • images – option to include embedded images and also set the display size
  • tweetId – set the twitter username for share links

The Twitter Feed Plugin Components

There are several functions we need to use that will make up the complete twitter feed plugin:

  • The AJAX function that will call the Twitter API and dynamically generate the feed items.
  • A function to search the twitter text and generate clickable links from URLs.
  • A function to generate the reply, retweet and favourite share links for each tweet.
  • A function that will convert the tweet date to a relative “time since” date.

The Plugin Code

We are using a standard jQuery pattern to create the plugin. See comments in plugin code for more information on each section:

(function($){

	TwitterFeedObject = function(el, options) {
		this.create(el, options);
	};

	$.extend(TwitterFeedObject.prototype, {

		create: function(el, options) {

			// Set the default options
			this.defaults = {
				id: '', // enter username, twitter list ID or search keyword
				retweets: true, // include/exclude retweets
				replies: true, // include/exclude replies
				avatar: true, // include/exclude user avatar
				results: 10, // number of results to display
				images: '', // large w: 786 h: 346, thumb w: 150 h: 150, medium w: 600 h: 264, small w: 340 h 150
				tweetId: '' // twitter username for share links
			};

			var o = $.extend(true,this.defaults,options);

			// Add ul tag to target element
			$(el).append('<ul class="stream"></ul>');

			// Set Twitter API url
			var url = 'https://api.twitter.com/1/statuses/user_timeline.json?screen_name='+o.id+'&count='+o.results+'&include_entities=true&include_rts='+o.retweets+'&exclude_replies='+ o.replies+'&callback=?';

			// Check if search feed & change API url if true
			var cq = o.id.split('#');
			if(cq.length > 1){
				var rts = o.retweets == false ? '+exclude:retweets' : '' ;
				url = 'https://search.twitter.com/search.json?q='+encodeURIComponent(cq[1])+rts+'&rpp='+o.results+'&include_entities=true&result_type=mixed';
			}

			// jQuery AJAX call to Twitter API
			jQuery.ajax({
				url: url,
				cache: true,
				dataType: 'jsonp',
				success: function(a){

					if(cq.length > 1){a = a.results} ;

					$.each(a, function(i,item){
						if(i < o.results){
							var html = '<li>',
								d = item.created_at,
								user = cq.length > 1 ? item.from_user : item.user.screen_name,
								name = cq.length > 1 ? item.from_user_name : item.user.name,
								avatar = cq.length > 1 ? item.profile_image_url : item.user.profile_image_url ;

							html += o.avatar == true ? '<a href="http://www.twitter.com/'+user+'" class="thumb"><img src="'+avatar+'" alt="" /></a>' : '' ;
							html += '<a href="http://www.twitter.com/'+user+'" class="user"><strong>'+name+'</strong> @'+user+'</a>';
							html += linkify(item.text);

							// Show images if images: true
							if(o.images != '' && item.entities.media){
								$.each(item.entities.media, function(i,media){
									html += '<a href="'+media.media_url+'" class="twitter-image"><img src="'+media.media_url+':'+o.images+'" alt="" /></a>';
								});
							}

							// Add share links
							html += '<span class="section-share">'+shareLink(item.title,item.id_str,o.tweetId)+'</span>';

							// Get time since
							d = d != '' ? html += '<span class="date">'+nicetime(new Date(d).getTime())+'</span></li>' : '' ;
						}

						// Add twitter feed items to stream
						$('.stream',el).append(html).slideDown();
					});
				},
				complete: function(){

					// Code to open new popup window for share links + open other links in new browser tab
					$('.stream a',el).click(function(e){
						if($(this).parent().hasClass('section-share')){
							var u = $(this).attr('href');
							window.open(u,'sharer','toolbar=0,status=0,width=626,height=436');
							return false;
						} else {
							if(external){this.target = '_blank';}
						}
					});
				}
			});
		}
	});

	$.fn.dcTwitterFeed = function(options, callback){
		var d = {};
		this.each(function(){
			var s = $(this);
			d = s.data("twitterfeed");
			if (!d){
				d = new TwitterFeedObject(this, options, callback);
				s.data("twitterfeed", d);
			}
		});
		return d;
	};

	// Function to convert URLs in twitter feed text to links
	function linkify(text){
		text = text.replace(
			/((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
			function(url){
				var full_url = !url.match('^https?:\/\/') ? 'http://' + url : url ;
				return '<a href="' + full_url + '">' + url + '</a>';
			}
		);
		text = text.replace(/(^|\s)@(\w+)/g, '$1@<a href="http://www.twitter.com/$2">$2</a>');
		text = text.replace(/(^|\s)#(\w+)/g, '$1#<a href="http://twitter.com/search/%23$2">$2</a>');
		return text;
	}

	// Creates share links
	function shareLink(st,sq,tweetId){
		var s = '';
		var intent = 'https://twitter.com/intent/';
			s = '<a href="'+intent+'tweet?in_reply_to='+sq+'&via='+tweetId+'" class="share-reply"></a>';
			s += '<a href="'+intent+'retweet?tweet_id='+sq+'&via='+tweetId+'" class="share-retweet"></a>';
			s += '<a href="'+intent+'favorite?tweet_id='+sq+'" class="share-favorite"></a>';
		return s;
    }

	// Function to convert date to relative date
	function nicetime(a){
		a = $.browser.msie ? a.replace(/(\+\S+) (.*)/, '$2 $1') : a ;
		var d = Math.round((+new Date - a) / 1000), fuzzy;
		var chunks = new Array();
			chunks[0] = [60 * 60 * 24 * 365 , 'year'];
			chunks[1] = [60 * 60 * 24 * 30 , 'month'];
			chunks[2] = [60 * 60 * 24 * 7, 'week'];
			chunks[3] = [60 * 60 * 24 , 'day'];
			chunks[4] = [60 * 60 , 'hr'];
			chunks[5] = [60 , 'min'];
		var i = 0, j = chunks.length;
		for (i = 0; i < j; i++) {
			s = chunks[i][0];
			n = chunks[i][1];
			if ((xj = Math.floor(d / s)) != 0)
				break;
		}
		fuzzy = xj == 1 ? '1 '+n : xj+' '+n+'s';
		if (i + 1 < j) {
			s2 = chunks[i + 1][0];
			n2 = chunks[i + 1][1];
			if ( ((xj2 = Math.floor((d - (s * xj)) / s2)) != 0) )
				fuzzy += (xj2 == 1) ? ' + 1 '+n2 : ' + '+xj2+' '+n2+'s';
		}
		fuzzy += ' ago';
		return fuzzy;
    }

})(jQuery);

To make it easy to use copy the above plugin code into a file and name it jquery.twitter.feed.js.

Using Your jQuery Twitter Feed Plugin

1. Add the jQuery Library & Twitter Plugin

Add the plugin link & link to the jquery library to the document head as you would do with any other plugin:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.twitter.feed.js"></script>

2. Initialise the jQuery Twitter Feed Plugin

The minimum options required are the id for your twitter feed and the tweetId for the share links. There are 2 options for the id:

  • To show a feed from a username just enter the username (without the “@”) – e.g. “designchemical”
  • To show a feed for a search enter “#” followed by the the search term – e.g. “#designchemical”

To initialise the plugin add the following code in your document head after the links to the plugin file and the jQuery library:

<script type="text/JavaScript">
    $(document).ready(function() {
        $('#twitter-feed').dcTwitterFeed({
            id: '#designchemical',
            tweetId: 'designchemical'
        });
    });
</script>

To change any of the default options – e.g. disable replies, retweets & avatar image, show 20 feed items and include any embedded images:

<script type="text/JavaScript">
    $(document).ready(function() {
        $('#twitter-feed').dcTwitterFeed({
            id: '#designchemical',
            tweetId: 'designchemical',
            retweets: false,
            replies: false,
            avatar: false,
            results: 20,
            images: 'small'
        });
    });
</script>

3. The Twitter Feed CSS

The CSS is fairly easy – the feed items, which are returned as an unordered list plus styling for share links and the avatar image:

ul.stream {
	display: none;
}
ul.stream li {
	background: #fff;
	font: normal 13px/18px Arial, sans-serif;
	color: #333;
	position: relative;
	padding: 10px;
	margin: 0 0 2px 0;
	border: 1px solid #ccc;
	border-radius: 5px;
	-webkit-border-radius: 5px;
	-moz-border-radius: 5px;
}
ul.stream li a {
	color: #009999;
	text-decoration: none;
}
ul.stream li a:hover {
	text-decoration: underline;
}
ul.stream li .thumb img {
	padding: 1px;
	background: #fff;
	border: 1px solid #ececec;
	float: left;
	margin: 3px 7px 5px 0;
}
ul.stream li .user {
	display: block;
	font-size: 12px;
	color: #999;
}
ul.stream li a.user:hover {
	color: #999;
	text-decoration: none;
}
ul.stream li strong {
	font-size: 13px;
	color: #333;
}
ul.stream li a:hover strong {
	color: #009999;
	text-decoration: underline;
}
ul.stream li .twitter-image img {
	padding: 1px;
	background: #fff;
	border: 1px solid #ececec;
	clear: both;
	margin: 5px 0;
}
ul.stream li .date {
	display: block;
	clear: both;
	margin: 5px 0 0 0;
	line-height: 12px;
	color: #666;
	font-size: 11px;
	font-style: italic;
}
ul.stream li .section-share {
	bottom: 10px;
    right: 10px;
    position: absolute;
	z-index: 2;
}
ul.stream li .section-share a {
	display: block;
	width: 16px;
	height: 16px;
	float: left;
	margin: 0 2px 0 0;
	background: url(images/share.png) no-repeat 0 0;
}
ul.stream li .section-share a.share-retweet {
	background-position: 0 -16px;
}
ul.stream li .section-share a.share-favorite {
	background-position: 0 -32px;
}
ul.stream li .section-share a.share-reply:hover {
	background-position: -16px 0;
}
ul.stream li .section-share a.share-retweet:hover {
	background-position: -16px -16px;
}
ul.stream li .section-share a.share-favorite:hover {
	background-position: -16px -32px;
}

For the share links we have used an image sprite (see download files).

4. The HTML

The only HTML required in your page is an empty div tag with the ID set to the same as that used in the initalisation code – e.g. twitter-feed:

<div id="twitter-feed"></div>

Just place the above tag in your page between the body tags where you want the feed to appear.

Show Multiple Feeds Per Page

The plugin can show multiple feeds per page. To do this just multiple div tags with unique IDs and enter the initialisation code – e.g:

jQuery Code

<script type="text/JavaScript">
$(document).ready(function() {

    $('#twitter-feed-1').dcTwitterFeed({
		id: '#designchemical',
		tweetId: 'designchemical'
	});

	$('#twitter-feed-2').dcTwitterFeed({
		id: 'MCFC',
		tweetId: 'designchemical',
		results: 20,
		images: 'small'
	});
});
</script>

HTML Code

<div id="twitter-feed-1"></div>
<div id="twitter-feed-2"></div>

View jQuery Twitter Feed Plugin DemoDownload Demo Source Files

2 Comments

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags