Building A Twitter Ticker With jQuery
A great way to show off your tweets when you don’t have enough space is to use a marquee or even better, a ticker. Despite having previously made a tutorial on making a classic typewriter ticker I’m not actually too fussed with them. So as an alternative here is how to make a fading ticker. Here is what we will be making:
Twitter bird is from hongkiat.com. We are using it here for illustrative purposes only & no harm/infringement is meant.
The HTML
First let’s get some HTML down. I have developed this code so it works perfectly with the Twitter Stream WordPress plugin. Here is an example of the output needed for the jQuery to work correctly:
1 2 3 4 5 |
<div> <p>A tweet is here</p> <p>Another tweet here</p> <!-- cont... --> </div> |
With a little bit of modification the code should work fine for unordered lists too. I’ll try and add the modification in at the end.
The CSS
Next we need a bit of CSS to make it all pretty. If you want to change it feel free, these are just some settings that we here at Return True thought were quite nice, obviously the width will need to be modified in most cases. As I said I’m using Twitter Stream, because of that all my CSS is targeted at the twitter-stream
class. If you aren’t using Twitter Stream just give your div a different class & substitute twitter-stream
with it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
.twitter-stream { background: #d5e8ef; border: 1px solid #d5e8ef; -moz-border-radius: 7px; -webkit-border-radius: 7px; -khtml-border-radius: 7px; border-radius: 7px; padding: 10px; margin: 0 0 20px 0; font-size: 10px; color: #6e6f73; font-weight: bold; font-family: verdana; float: left; width: 87%; } .twitter-stream p { padding: 0px; margin: 0px; } .twitter-stream p a { color: #45799f; text-decoration: none; } |
The jQuery
Okay, now onto the difficult part. Let’s first take a look at the jQuery code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
jQuery(function($) { var opts = { el: '.twitter-stream', items: new Array(), count: 0, total: -1, delay: 6000, animate: true }; $(opts.el+' p').each(function(i) { opts.items[i] = $(this).html(); opts.total++; }).hide(); runTweeter(); function runTweeter() { if(opts.animate == true) { if($(opts.el+' p').length > 0) { $(opts.el).children('p').fadeOut(500, function() { $(this).parent(0).empty().append('<p style="display: none;">'+opts.items[opts.count]+'</p>').children('p').fadeIn(500); }); } else { $(opts.el).empty().append('<p style="display: none;">'+opts.items[opts.count]+'</p>').children('p').fadeIn(750); } } else { $(opts.el).empty().append('<p>'+opts.items[opts.count]+'</p>'); } setTimeout(function() { if(opts.count == opts.total) { opts.count = 0; } else { opts.count++; } runTweeter(); }, opts.delay); } }); |
I think I might try to make a jQuery plugin out of this eventually, but for now I thought it would be of more use to write out the whole code & explain what it all does.
First we have the traditional no conflict DOM ready. I used no conflict as I was developing in WordPress. Next we setup some options in an object. These options are pretty self explanatory. You will need to change el
to the class or ID of the div that holds the paragraphs (which contain the tweets). You can also change delay to change the length of time between each tweet. Animate is whether you wish the fade to be present between tweets. Otherwise they will just switch between each tweet. The other options should be left as they are or the ticker won’t work correctly.
Now for an explanation of the code. I was just going to make a jQuery plugin, as I said, but I wanted to be able to teach you guys something so I thought what better way than to explain how this works.
As we are going to remove the tweets from the page and replace them with a ticker we need to store each tweet. That’s what the this section does:
1 2 3 4 |
$(opts.el+' p').each(function(i) { opts.items[i] = $(this).html(); opts.total++; }).hide(); |
It uses the element defined as a base and loops through each paragraph found assigning the html of each paragraph to the items array created earlier. We also increment the total counter each time.
Next we tell our main function to run. Then we define said function. Let’s take a look at the next bit:
1 2 3 4 5 6 7 8 9 10 11 |
if(opts.animate == true) { if($(opts.el+' p').length > 0) { $(opts.el).children('p').fadeOut(500, function() { $(this).parent(0).empty().append('<p style="display: none;">'+opts.items[opts.count]+'</p>').children('p').fadeIn(500); }); } else { $(opts.el).empty().append('<p style="display: none;">'+opts.items[opts.count]+'</p>').children('p').fadeIn(750); } } else { $(opts.el).empty().append('<p>'+opts.items[opts.count]+'</p>'); } |
We check to see if you want any fancy animations. Yes? Then check if we already have a paragraph. Yes? Okay, select that paragraph and fade it out. Once complete select the parent (the div that holds the paragraphs), empty it and append the new tweet but with display set to none so it is hidden. Then select said created paragraph and fade it in. Got all that? If there isn’t any paragraphs yet we need to do all that again but without selecting the children & fading out or it causes some weirdness.
If we don’t want animation we simply empty the main element & append the new paragraph (tweet) to it.
One important thing to note in the code above is the opts.items[opts.count]
this grabs the correct tweet from the array. How? Well the count is incremented (a little later) each loop through.
Now let’s take a look at the final major piece of code:
1 2 3 4 5 6 7 8 |
setTimeout(function() { if(opts.count == opts.total) { opts.count = 0; } else { opts.count++; } runTweeter(); }, opts.delay); |
This code sets a timeout so our code will run over and over. We check if we have reached the last paragraph or tweet. If we have we need to reset to 0 and start from the beginning again. Otherwise we can add 1 to out count and run the main function again. This all occurs after the delay which we set in the options at the start.
Confused Yet?!
Okay so all that might be a little confusing, but hopefully by going through the code a little I’ve managed to help someone out there. If not all you have to do is copy the code & change the el: '.twitter-stream'
and you are ready to rock. If you are using Twitter Stream you just need to copy the code.
Example Please…
If you want to see an example you can find one here.
I hope this tutorial has been helpful. Let me know if you have any questions or problems via the comments & I’ll get back to you as soon as I can.
17 Comments
Jaume
Hi!
your ticker is very good, but I was wondering if I can set a search query and display the twitter posts for that search.
Thanks!
Paul Robinson
You could, but not by using the Twitter Stream plugin. You could still use the code that makes the ticker, but you’d have to use PHP to code your own Twitter app.
I’d advise using the TwitterOAuth class which you can get at github to build it. Twitter advise against anon queries now, plus if you are on a shared server you’ll run out of API requests very quickly without logging in via OAuth.
If you have any problems using the class let me know & I’ll see if I can knock up a quick tutorial on how to use it.
AP Design
Here’s full code, including PHP script. Just for anyone whose new to coding etc. (Replace USERNAME with twitter USERNAME)
PHP Script taken from – http://blog.lylo.co.uk/2009/02/04/how-to-display-twitter-updates-using-php-and-without-using-curl/
Paul Robinson
Great code. Thanks for posting it.
If you are on a shared server you might have a few problems though as you aren’t providing any authentication credentials. This will cause you to run out of API requests very quickly.
There isn’t an easy way to get around that though without using OAuth. I’ll try and get a tutorial on how to use it eventually. I’ve just been really busy, and my router crapped out 2 days ago so I’ve been offline for a couple of days.
Bram
Thank you very much for the code Paul.
We are trying to use it but we’ve a problem with some characters like (á, Ó, ñ, etc.)
Although we knew nothing about jquery, we
ve included your twitter ticker easily, (http://www.forpe.es/ej_twitter.php), due to your blog and AP Design
s post.But we need a little help to fix the characters problem.
Could you give us a hand?
Bram.
Paul Robinson
Hi Bram,
I’m not seeing any problem with UTF-8 characters on the page provided. However I’m using Google Chrome. It could be a problem in some browsers as it looks as if they are being placed on the page as their literal characters instead of the entity version.
If you are using the PHP code provided by AP Design try running
htmlentities()
on the resulting content. So in the PHP code above on line 108 you would add:That’s the only thing I can think of that might be causing those type of characters to display incorrectly. Let me know how it goes. 😉
Bram
Thanks Paul,
I
ve added your line to the code but problem still exists. Also I
ve download Chrome but the characters are wrong:http://www.forpe.es/ej_twitter-paul.php
For example, in our last tweet:
(En Navarra la FP está en auge)
The ticker shows:
En Navarra la FP está en auge
I appreciate your help.
Greetings.
Bram.
Joln
Sweet as hell! 🙂
Paul Robinson
Thanks. 🙂
Kevin
Your Comment
Kevin
This is great! Thanks for sharing. I have run into one problem. In Internet Explorer 9 (beta), the animate feature does not work. The posts display for about a half second and quickly hide. If I set ‘animate’ to false, the posts show correctly without animation. Do you know what might be causing this?
Paul Robinson
Hi Kevin.
From what I can find it is a known bug with IE9 and nothing to do with jQuery. I’d say try your best to work around it for the minute, and hope the IE9 dev team fix the ticket that another coder has already logged on their bug tracking service.
Sorry I can’t be of more help. Let’s hope the IE team get it sorted before final release at the least.
Kevin
Thanks for your help, Paul!
Paul Robinson
No worries. I’m hoping IE will have a fix out for it soon. 😉
Michelle
Hey Paul,
I’m new to this, and I can’t seem to find where I would put my username in the code you have posted.
Any help would be greatly appreciated!
Thanks
Paul Robinson
Hi Michelle,
This code is just the code to build the ticker, you would need another piece of code to grab your tweets. In this case I used the WordPress plugin Twitter Stream, but it could be anything such as SeaOfClouds Twitter plugin for jQuery.
Sorry about that. There are so many ways to pull in Tweets I decided to leave that choice to the user of the code. If you need any other help I do offer coding services, just visit my Hire Me page for more info.