Tweet Carousel - a scrolling twitter feed animation (API 1.1)

19 August, 2013 by Tom Elliott

This is the second twitter feed animation I’ve created as part of my jQuery Twitter series for the new AP1 1.1. A carousel style scrolling twitter feed was one of the more frequently requested types of twitter animation.

View the Tweet Carousel demo here.

The carousel will load in the latest tweets, with the most recent at the top, scrolling through them based on a time interval. There are options to adjust how fast the tweets should slide, how many tweets to scroll by and how long the delay between the sliding.

Tweet Carousel has been tested for compatibility in all major browsers including Chrome, FireFox, IE 8, IE 9, IE 10, Safari and Opera

Step 1 – Authentication

If you’ve read any of my previous Twitter Feed tutorials, you’ll know by now that as we have to work with Twitter’s API 1.1, all endpoints need to be authenticated. The first thing you should do is head over to my Twitter authentication guide to get your twitter user timeline (or search stream) authenticated and tweets list output as JSON format.

This solution is PHP based but alternatives are available if you prefer to work in a different server side language.

Step 2 – The Twitter Carousel

Got your tweets output in raw JSON format? Great. The easiest thing next would be to grab all the JavaScript, CSS and HTML from the Tweet Carousel demo, replacing the PHP file in the $.getJSON request with the script you created in step 1. If you get an error, there’s plenty of troubleshooting tips (along with more info) over at the static feed tutorial.

If you are already using the static twitter feed and want to upgrade to this one, it would probably be best to use the new JS and CSS as a number of changes have been made and then apply any specific styles.

Tweet Carousel Breakdown

Let’s run through some of the variables and the main function that controls how the Tweet Carousel operates. At the beginning of the JavaScript there are a load of parameters – generic feed parameters (which we’ve used on the static feed) and some carousel specific variables as below:

  1. The feedheight variable sets the height of the Tweet Carousel. The Carousel needs to have a fixed height because if it kept adjusting to fit the containing tweets of different heights, it would look odd and affect any HTML elements sitting below the Carousel.
  2. pausetime sets the delay between the sliding of tweets in milliseconds. It’s good to set this quite high to give people a chance to read the tweets.
  3. slidetime determines how long it takes to slide the tweets into the next position. This defaults to 2 seconds which seems to be a good length when scrolling 3 tweets.
  4. tweetshift determines how many tweets to scroll by after the pausetime delay. tweetshift should be a factor of the totaltweets, i.e. totaltweets divided by tweetshift should give a whole number. If your scrolling 2 tweets at a time, the totaltweets should be an even number for example.
  5. The boolean slideinitial will determine if the tweets should initially appear instantly or scroll into view.

The main carousel function is below:

function tweetcarousel() {
  var currenttweet = 1;
  var lasttweet = totaltweets;
  var tweetheight = new Array();
  var totalheight  = 0;
  var sliderheight = feedheight;

  for (var i=1; i<=totaltweets; i++) {
	  tweetheight[i] = parseInt($('#t'+i).css('height')) + parseInt($('#t'+i).css('padding-top')) + parseInt($('#t'+i).css('padding-bottom'));
	  if (slideinitial == false) {
		  sliderheight = 0;
	  }
	  if (i > 1) {

		  $('#t'+i).css('top', tweetheight[i-1] + totalheight + sliderheight);
		  $('#t'+i).animate({'top':tweetheight[i-1]+ totalheight}, slidetime);
		  totalheight += tweetheight[i-1];
	  } else {
		  $('#t'+i).css('top', sliderheight);
		  $('#t'+i).animate({'top':0}, slidetime);
	  }
  }
  totalheight += tweetheight[totaltweets];

  setInterval(scrolltweets, pausetime);

  function scrolltweets() {
	  var currentheight = 0;
	  //totalheight = 0;
	  for (var i=0; i<tweetshift; i++) {
		  var nexttweet = currenttweet+i;
		  if (nexttweet > totaltweets) {
			  nexttweet -= totaltweets;
		  }
		  console.log(nexttweet + " "+ currenttweet);
		  currentheight += tweetheight[nexttweet];
	  }

	  for (var i=1; i<=totaltweets; i++) {
		  $('#t'+i).animate({'top': (parseInt($('#t'+i).css('top'))-currentheight) }, slidetime, function(){

			  var animatedid = parseInt($(this).attr('id').substr(1,2));

			  if (animatedid==totaltweets) {
				  for (j=1; j<=totaltweets; j++) {
					  if (parseInt($('#t'+j).css('top')) < -50) {
						  var toppos = parseInt($('#t'+lasttweet).css('top')) + tweetheight[lasttweet];
						  $('#t'+j).css('top', toppos);
						  lasttweet = j;

						  if (currenttweet >= totaltweets) {
							  var newcurrent = currenttweet - totaltweets + 1;
							  currenttweet = newcurrent;
						  } else {
							  currenttweet++;
						  };
					  }
				  }								

			  }
		  });
	  }
   }
}
tweetcarousel();

In a nutshell, the function will first loop through the total number of tweets, recording the different heights of each tweet in an array and setting the total height of the combined tweets before animating them into view.

A timer is set to scroll the tweets based on the delay interval. This will then loop through and scroll all tweets at once and if any of the tweets have scrolled above the top of the feed container (CSS set to overflow:hidden), then the top position of that tweet is set to the position of the last tweet in the feed list.

If you want to turn on the tweet intents (for reply, retweet and favorite), you can do so by setting showtweetactions to true. This is disabled by default however since people are less likely to want to interact with the Carousel if the tweets within are moving.

There are still a few features I want to add to this. For example having the twitter feed checking for new tweets and refreshing the list automatically.



Creating a Twitter Search & Analytics tool »


18 Comments

  • Walter says:

    Nicely done.

    A refresh and it will be perfect.

  • Ellen says:

    Thank you very much for this great tutorial. Would there be any way to create a horizontal scroll using a similar method please?

  • Mike says:

    If we can make this work with “Search” instead of personal tweets that would be awsome!

  • ALINE says:

    Hi. Can appear the images(pictures) posted in the timeline ? How can i do it appear (and not only teh link)?

  • Joe says:

    I’m having trouble downloading the code. You mention ‘The easiest thing next would be to grab all the JavaScript, CSS and HTML from the Tweet Carousel demo,’ but when I click or down load the link I only get the html. Is there another link to down load the code I’m just not seeing?

    Love the tutorial! I would also be interested in the refresh code, and like the idea of horizontal scrolling.

    • Tom Elliott says:

      Hi Joe, thanks – yes rather than downloading the link, if you go to the demo page and then view source – that will give you the HTML. There’s also a link within the HTML to the JS and CSS file which you can follow and paste from there. Hope that helps 🙂

  • Costas says:

    a horizontal version of the carousel would be perfect

  • Erfan says:

    Tom Elliott
    I want to it slide horizontaly with next and prev button and one tweets at a time. How could i do it ?Plz help me

  • Joost says:

    Thanks again for the tutorial. I have been using it for some time now.

    I have one issue unfortunately. Sometimes there are not enough tweets to fill the var ‘totaltweets’. This breaks the carrousel. Not only does it show blank pages (obviously), but it also ends at the end of the first animation and doesn’t loop back to the first tweet. Any idea how to fix this?

    • mark Creer says:

      Joost or Tom :
      Any luck getting this to handle a small number of Tweets ?
      I’m doing site for a new company with 1 tweet – so the panel goes blank and does not recycle to the top.

      Great work Tom – thanks!

  • Laurel says:

    So I’m on the right track with your tutorial (which is fantastic by the way), I know the feed is almost there, but when I load the page i get a ‘Requested page not found’ 404 alert. I can’t seem to figure out what’s going on or find any broken file paths?

    Got any suggestions? Would really appreciate any info.

  • Laurel says:

    So as it turns out, i was trying to implement this into a WordPress website. The issue is the file path! It’s sort of figured out…

  • AncA Lev Bonaparte Yachine says:

    thanks alot so usefull 🙂

  • Mark says:

    Hi Tom – any idea how to handle images in Tweets?
    I wouldn’t mind if it just ignored them but they break the script – it stops at the first Tweet with an image and then refuses to cycle. Google doesn’t show me anything useful so far either…

  • Avinash Singh says:

    i’m getting below error…

    GET http://123.63.245.233:81/crossdomain.xml 404 (Not Found)

  • John says:

    Tom,

    Sorry, guess I don’t know how to post. Bottom line is the first return line in the js left out the _blank to get it to open in new widow or tab.

  • Bobby says:

    Tom,
    Can you please share how to access the media_url to display an image?

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    css.php