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!





116 Comments
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!