Notice: Undefined index: order_next_posts in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 194

Notice: Undefined index: post_link_target in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 195

Notice: Undefined index: posts_featured_size in /nas/content/live/gadgetmag/wp-content/plugins/smart-scroll-posts/smart-scroll-posts.php on line 196

Create interactive animations from a Twitter feed

Twitter streams don’t have to be boring lists – there’s a world of ways to visualise what people are tweeting, so let’s get creative…

Create interactive animations from a Twitter feed

Twitter is a great tool for getting the pulse of the world, and is becoming more and more pervasive as mainstream media starts to include tweets in audience participation. The majority of users access and use Twitter through the website, but thanks to the public API, we can now take the data from Twitter and do something a little different with it.

This tutorial is inspired by the excellent Tori’s Eye site, found at This is a visualisation of a Twitter stream that places some stylised birds into a landscape, flying across the screen to deliver tweets. It uses the Twitter JSON API to grab tweets from the Twitter timeline and a smattering of JavaScript to present them in an engaging manner.

In our version we’ll simplify how this is done, but we’ll be using the same basic principles to create an animation along similar lines to Tori’s Eye. Once you’ve completed this workshop you should have the understanding and tools at your disposal to create your own visualisation in new and exciting ways. Perhaps you’ll feel compelled to let us know what you come up with by Tweeting us (naturally) via @WebDesignerMag.

Tutorial files: download here.

01. Design a mockup

We start off by taking direct inspiration from the Tori’s Eye visualisation and designing a replica inside Illustrator. Our file can be found on the disc, but to get the textures we’ve used you’ll need to visit and search for paper and rusty metal stock. Note that we’ve separated out the background and the birds onto different layers for easier export later.

02. Output to PNG

Once we’re happy with the overall visual look, we need to export the graphics in a format suitable for use in the final HTML design. The background can be a straight JPEG as it doesn’t need any transparency. The birds, however, must be in PNG format. You need to isolate one bird and export it – this will become the master bird graphic.

03. Other elements

In Tori’s Eye the trees are separated into a layer above the birds, so that the birds can fly behind them. We’ve chosen not to mimic this for ease of understanding, but we did separate out the trees onto their own transparent PNG layer just in case we want to replicate the layers later down the line. You can find all our graphics on this month’s CD.

04. Create the HTML structure

We’ve got our graphics sorted, so now let’s create the basic HTML structure. Add the step code to a new page in your web editor. We’ll create some basic CSS rules, and to keep it simple we’ll retain all our style and script code in this one file. If you want a quick step up, we’ve included the basic HTML page on the disc – just open up ‘start.html’.

[sourcecode language=”html”]
<title>Twitter Animation</title>
<div id="container">
<div id="trees">
<div id="tweetscontainer">

05.  Add some CSS

Apply this CSS; the full code is on the disc.

 body {
  font-family:    arial, helv, sans- serif;
 font-size:    66%;
 background:    #f9f9f9;
 padding:    20px;
 #container {
 position:    relative;
 width:            1024px;
 height:        700px;
 margin:        auto;
 background:  transparent url(styles/background.jpg) no-repeat top left;

06. Grab jQuery

Visit and download the latest version of the library. jQuery makes it easy for us to interact with different elements on the page and create animations. To this end, we’ll install it at the top of our page, and set up a function beneath ready to hold all of the code to make our visualisation work.

<script type="text/javascript"  src="scripts/jquery.js"></script>
 <script type="text/javascript">
 // Your jQuery code will slot in     here

07. Connect to Twitter

Twitter has an API that’s publicly accessible. If you’re creating a full application, you may want to sign up for a specific developer API key, but for our purposes we’re just going to use the public version. We can call this using jQuery’s JSON method. Note that we’re passing in a search term that will return matching tweets – change this to suit you. Full code is on the CD.

var url = " search.json?q=iphone&rpp=15&callback=?";
 var tweets = $('<ul id="tweets">').         appendTo("#tweetscontainer");
 $.getJSON(url,  function(data){
 // Do something with the data returned

08. Parsing JSON

The data is returned from Twitter as a JSON object. JSON is a straightforward way to wrap data as a set of keys and values in an array. All we need to do is to iterate through the returned array and generate HTML. code from the values for each set of data. Add the code below to do this; full code is on the cover disc.

$.getJSON(url,  function(data){
 $.each(data.results, function(i,item){
 tweets.append('<li><div><img src="'  + item.profile_image_url +'" alt="' +
 item.from_user + '" width="73"           height="73" /><p><a href="http://twitter.       com/'+item.from_user
 +'/statuses/''" title="Click    here to view this on twitter">'+item.from_      user+'</a> at
 '+item.created_at+': '+item.text.           replace(/(w+://[A-Za-z0-9-_]+.              [A-Za-z0-9-_:%&?/.=]+)/gi, '<a
 href="$1">$1</a>').replace(/             [@]+([A-Za-z0-9-_]+)/gi, '<a href="http://$1">@$1</

09. Output results

Our code generates a list item (<li>) for each tweet, wrapping the actual contents of the tweet inside a <div> tag. We’ll use this later on to show and hide the tweet, but for now you should have 15 list items once the code has finished doing its work.

10. Test it out

It’s worth taking a moment to make sure your script is loading the tweets and outputting them in HTML. Although this will look pretty ugly, it’s a quick way to verify everything is working as it should. Once you’ve loaded it in your browser and observed all your tweets loading, you can move on to the next step.

11. More style

Let’s deal with the ugliness first of all. Each list item will become a bird that we animate across the screen. We’ve already set our container to have overflow:hidden, so we’ll be able to position our birds so that they start off outside the visible area, then animate them into position. Add the CSS below to set the start position for each <li>. Full code is on the disc.

#tweets {
 position:    absolute;
 top: 0;
 left:  0;
 width:  2000px;
 margin-left:  -300px;

12. Create speed variables for the birdies

We’re going to generate a speed variable for each list item and run a function periodically to set the position of the bird. Each time the function runs, we’ll use the speed variable to reposition the list item by a set amount, and as we repeatedly run our function, so the list items will appear to be animated across the page.

13. Generate random values

We’re going to use random numbers to set the speed of each bird so that the birds don’t all fly across the screen at the same rate. JavaScript lets us generate random numbers using the Math.random() function. Add the code below to call up a random number between 0 and 9 to represent the speed of each bird.

var speed=Math.floor(Math.random()*10)+1;     

14. Set the start position

We don’t, however, want them all to be at the same vertical level, otherwise it’ll become very monotonous – so to avoid this we need to set a random starting position. We also need to store the speed value for each bird, and we can do this using the .data() method in jQuery. Add the code below to set the vertical position and store the speed. We also set the horizontal position to offset a little for each <li>.

var offsettop=Math.floor(Math. random()*400)+10;
 $("#tweets li:last").data("speed",speed).css({top:offsettop,right:2000+(i*30)});

15. Get things moving

Although jQuery has the animate() method, we’ll use a straight setInterval function and set the position of each bird using CSS alone. This will enable us to control the frame rate more easily and give more predictable results. To start we’ll need a function that fires periodically; add the code below to create this.

var t = setInterval(function(){
 // we’ll set the position of each bird every 30 milliseconds

16. Get things moving 2

Each time the function fires, we want to update the position of every bird to its new location on screen. Add this step’s code to grab the speed for each bird from the data() object and update the position of the bird accordingly. Again, full code is on the CD.

var t = setInterval(function(){
 $("#tweets li").each(function(){
 // grab the speed variable
 speed = $(this).data("speed");
 // and the current position
 xpos = $(this).css("left");
 // if the bird is off the left hand side of the screen, reset it to the right

17. Time to test

It’s time to open your page and test it out. All being well, after a short delay while the Twitter feed loads, you should see birds flying across the screen with tweets sitting on top of them. We’re nearly there now – just a bit of tidying up to do!

18. Pause for thought

The first thing that we notice is that it’s a little tricky to read the tweets as they zoom past. Let’s make the bird stop in position when the cursor is hovered over it. We’ll want the bird to carry on moving when we mouse off the bird, so add a clause to the animation function, and add a class to the bird as we mouse over to exclude it from the animation.

$("#tweets li").not(".hover").each(functio…
 $("#tweets li").hover(function(){

19. More style

Now we’ve got our birds flying across the screen, it would be nice to have the actual tweets appearing only when each bird is moused over. We’ll apply a little more panache to the way the tweets are displayed at the same time. Add the CSS below to hide the tweets until mouseover, and get them looking a bit more presentable. You will find the full code for this step on the cover disc.

#tweets li div {
 display:  none;
 padding:             10px;
 background:    rgba(0,0,0,0.7);
 color:                 #fff;
 min-height:    93px;
 margin-top:    100px;

20. Another quick test

If you test again now you should see the birds without all the tweets sitting on top of them, and as you move your mouse over the top of a bird it should stop in its tracks, and the tweet should then display underneath it. With these changes, we think the page is looking much slicker, plus it makes the Twitter stream much more fun to interact with!

21. Tweak to suit

When you test out your page you’ll almost certainly find that you want to modify some of the values – especially the random number generation and setInterval delay, as this will affect how quickly the birds fly across the screen. Try experimenting with a few different values to see the effect they have, and tweak values to taste.

22. Take it to the next level

Your overall visualisation should now be working nicely. Test in all your target browsers and check that everything works as it should. You might now want to consider extending the functionality so that the user can input their own search term, or so that some birds are bigger/faster than others – get creative and show us what you produce. You might end up in the Lightbox!