Creating Your Own Twitter Trends Widget
Twitter is big, big news at the minute and is likely to be for years to come. In many cases it is now people's first port of call (mine included) to find breaking news from around the globe, just look at the gentleman who unsuspectedly Tweeted about a loud helicopter noise coming from near his coffee shop in Abbottabad... he's now a world wide star!
We're not going to look at anything quite so serious in this article, we're going to have a nosey into what people are saying about the lovely city of Sheffield. This widget could be used in many different scenarios, it could easily be extended into a simple one page website on a specified subject or included into the sidebar or footer of an existing website as a quick reference resource.
Step One
As always, we need to set up our HTML document giving us our base structure. Our first HTML snippet goes within this <head> tags of the document, here we include Google's CDN version of jQuery and our external Javascript and CSS documents. The second HTML snippet shows the makup required for our demo, this should be placed within the document's <body> tags.
HTML
<link rel="stylesheet" type="text/css" href="all.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
<title>What are people saying about Sheffield?</title>
HTML
<div id="container">
<h1>What are people saying about Sheffield?</h1>
<div id="tweets"></div>
</div>
That's all we need in terms of HTML for this project, everthing else is created dynamically with jQuery.
Step Two
Next up, the fun bit, writing the jQuery to fetch the Tweets and add them to the DOM. We're going to use a technology called JSON (JavaScript Object Notation) to make our request to Twitter. Once we have our result from Twitter we then loop around and manipulate the result data to form out Tweet listing. A nifty little snippet is used when constructing our Tweet (kudos to CSS Tricks) which converts URLs to wokring links, hashed items to Twitter search links and also links @ replies to the user's profile.
jQuery
[javascript]
$(document).ready(function() {
// json call to twitter to request tweets containing our keyword, in this case 'sheffield'
$.getJSON("http://search.twitter.com/search.json?q=sheffield&callback=?", function(data) {
// loop around the result
$.each(data.results, function() {
var text = this.text;
if(text.charAt(0) != '@') {
// construct tweet and add append to our #tweets div
var tweet = $("<div></div>").addClass('tweet').html(text);
// analyse our tweet text and turn urls into working links, hash tags into search links, and @replies into profile links.
tweet.html('<div class="content">' +
tweet.html()
.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>')
.replace(/(^|\s)#(\w+)/g,'$1<a href="http://search.twitter.com/search?q=%23$2">#$2</a>')
.replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/$2">@$2</a>')
+ '<br /><a href="http://www.twitter.com/' + this.from_user + '/status/' + this.id_str + '" class="view" target="_blank">' + $.timeSinceTweet(this.created_at) + '</a></div>'
)
.prepend('<a href="http://www.twitter.com/' + this.from_user + '" target="_blank"><img src="' + this.profile_image_url + '" width="48" height="48" /></a>')
.appendTo('#tweets')
.fadeIn();
}
});
});
});
[/javascript]
You may notice the call to a $.timeSinceTweet function within our snippet, you can find this within the source download. The $.timeSinceTweet function takes the created time of the Tweet and then returns a Twitter style time since string (i.e. 1 minute ago, 20 minutes ago, 2 days ago).
Step Three
The final step is to style up our result. I've added a very minimal set of styles for the purposes of this demo.
CSS
[css]
body {
font: 12px/20px Arial, Helvetica, sans-serif;
color: #161616;
}
a { color: #666; text-decoration: underline; }
a:hover { text-decoration: none; }
h1 {
height: 27px;
margin: 25px 0;
background: url(logo.png) no-repeat 0 0;
text-indent: -9999px;
}
#container { width: 500px; margin: 0 auto; }
#tweets .tweet {
padding: 10px 20px;
font-size: 15px;
position: relative;
border-bottom: 1px dashed #ededed;
overflow: hidden;
}
#tweets .tweet img { margin-right: 12px; float: left; }
#tweets .tweet .content { width: 400px; float: left; }
#tweets .tweet .content a.view { font-size: 10px; }
[/css]
Have a go at creating your own widget and let me know how you get on. Twitter's Search API offers an excellent reference insight into the posibilities available to anyone wanting to customise our widget, especially the operators listing which shows what parameters are supported.
Twitter have recently released an updated version of the REST API which uses a slight different syntax to the one explained in this post, please see https://dev.twitter.com/docs/api/1.1/get/search/tweets for more details.
5 Comments
Does this refresh on its own?
Post replyHi Katie.
It doesn't refresh by itself in its present state. One option would be to add a Javascript interval to run the getJSON request at set timed intervals.
I hope this helps.
Stewart
Post replyHello Stewart,
Tried to get it working by putting the code inside a widget box . Not working even when I put it in the body .
Shall appreciate your help.
$(document).ready(function() {
// json call to twitter to request yweets containing our keyword, in this case 'sheffield'
$.getJSON("http://search.twitter.com/search.json?q=sheffield&callback=?", function(data) {
// loop around the result
$.each(data.results, function() {
var text = this.text;
if(text.charAt(0) != '@') {
// construct tweet and add append to our #tweets div
var tweet = $("").addClass('tweet').html(text);
// analyse our tweet text and turn urls into working links, hash tags into search links, and @replies into profile links.
tweet.html('' +
tweet.html()
.replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'$1')
.replace(/(^|\s)#(\w+)/g,'$1#$2')
.replace(/(^|\s)@(\w+)/g,'$1@$2')
+ '' + $.timeSinceTweet(this.created_at) + ''
)
.prepend('')
.appendTo('#tweets')
.fadeIn();
}
});
});
});
What are people saying about Sheffield?
Post replyHi Sreedhar
Do you have a link to where you have tried to implement the script so I can help you further please?
Cheers
Stu
Post replyHello Stewart,
Many thanks for your reply.
I have your code in a widget on
http://lastingrose.blogspot.com/
Please E mail me for login details if you need.
I guess the problem is with your main.js which should reside in the server but not possible in this case as it is blogspot. I don't have access to a host at this time to upload the script and link to it.
Post replyCould you publish or e mail me a text version.
Many thanks again for your help. Much appreciate.
I have previously had to abandon several scripts due to jquerry conflicts.
Hello,
Post replyNice widget! Is it possible to get more then 10 twitter results?
Thanks for your help!
Hi Pim
There are a whole load of options you can use with the widget, see https://dev.twitter.com/docs/api/1/get/search
The return more than 10 results assign a number greater than 10 to the rpp param in the Twitter query string.
E.g. To fetch 20 results rather than 10
Post replyhttp://search.twitter.com/search.json?q=sheffield&since_id=" + since + "&callback=?
changes to
http://search.twitter.com/search.json?q=sheffield&since_id=" + since + "&rpp=20&callback=?
Hey
Excellent post, thanks a lot, really helped me !!
Post replyHi,
Post replyI tried to search for hashtags, for example #twitter but it doesn't show anything, does it support hashtags?
Hi Payam
You'll need to use the Hex ASCII character for the hash symbol, which is '%23'. For example, to search for #twitter you would use %23twitter in your Twitter query string.
Thanks
Stu
Post replyLeave a comment