Creating a simple animated twitter feed fade rotation

03 August, 2013 by Tom Elliott

I’ve done a few posts on Web Dev Door tackling the new Twitter API 1.1 authentication for Twitter feeds. One of the more common feature requests has been adding animation to the tweets. This first Twitter animation post runs through the code needed to create a simple fading twitter feed ticker, with tweets fading in and out one at a time. View the tweet fade demo (user timeline) or tweet fade demo (search).

First things first though. As we’re working with the new API 1.1 that requires all endpoints to be authenticated, you’ll need to get the twitter stream you want to use authenticated and output as JSON encoded tweets. Head over to my Twitter authentication tutorial for a step by step. This is a PHP based solution but there are libraries available for other languages if you prefer to use them.

Once you have your twitter feed authenticated and output as JSON, you’ll probably want to head over to the twitter fade animation demo to grab all the HTML, CSS and JavaScript. You’ll need to replace the PHP file path in the $.getJSON request to whatever you named your authentication script. For more details on the variables used, or if you get any errors when trying to add the code in the demo, the static feed tutorial has a load of troubleshooting and tips which should help.

The fading tweet animation uses the function below. This sets up the fading tweet ticker by initially hiding all the tweets, fading in the first tweet with subsequent tweets fading in and out after an interval period. The variable tweetdelaytime controls the time (in milliseconds) to display a tweet before fading away. tweetfadetime obviously controls how long it takes for a tweet to fade and the variables fadeoffsetin and fadeoffsetout control the number of pixels each tweet can move up or down as they are fading in or out. Set these to 0 to disable the movement.

function animatetweets() {
	var tweetdelaytime = 5000;
	var tweetfadetime = 500;
	var fadeoffsetin = 30;
	var fadeoffsetout = -30;				

	var starttweet = 1;
	var animatetweet = starttweet;

	for (var i=starttweet; i<displayCounter; i++) {
		$('#tw'+i).css({'display': 'none', 'opacity':0});
	}
	fadetweet();
	function fadetweet(){

		$('#tw'+animatetweet).css({'display': 'block'});
		$('#tw'+animatetweet).css('margin-top', -fadeoffsetin);
		$('#tw'+animatetweet).animate({'opacity': 1, 'margin-top':0},tweetfadetime, function(){
			$('#tw'+animatetweet).delay(tweetdelaytime).animate({'opacity': 0, 'margin-top':fadeoffsetout},tweetfadetime, function(){
				$('#tw'+animatetweet).css({'display': 'none', 'margin-top':0});
				if (animatetweet < displayCounter-2+starttweet) {
					animatetweet++;
				} else {
					animatetweet = 0+starttweet;
				}
				setTimeout(fadetweet, 0);
			});
		});
	}
}
animatetweets();

If you want the tweets to fade in or out below the container, then you’ll probably want to give the CSS div container #twitter-feed a fixed height and set the overflow to hidden so that the container doesn’t expand to fit the height of the moving tweet. This works best when the width of the feed is quite wide so tweets fit on 1 or 2 lines.

I have also disabled the tweet intents (reply, favourite and retweet) as I think people would be less likley to want to interact with an animated twitter feed. These can be turned on easily using the parameters at the beginning of the JavaScript in the demo.

Some of you may already be using the code from the custom jQuery twitter feed or twitter feed for search tutorials and want to upgrade to the animated tweets without starting from fresh or having to restyle your twitter feed. It should be easy modify this by adding the function above to the twitter feed JavaScript file. You need to add this within the $.getJSON function, before the error handling – if you’re not sure, check the demo code. You will also need to do the following:

  1. JavaScript: Check each ‘twitter-article’ has an ID as on Line ~67
  2. JavaScript: Update line ~18 and ~19 to enclose the header HTML with ‘twitter-header’ div
  3. CSS: add the #twitter-header style from the demo
  4. CSS: Updated #twitter-feed container to include a minimum height.

I’m also working on a Twitter feed carousel, which I’ll have up shortly. 🙂



Creating a Twitter Search & Analytics tool »


69 Comments

  • John says:

    Thank you so much for this useful tutorial! Your website is such a great resource.

    How can the fade jscript be used in conjunction with Twitter searches, specifically related to your other tutorial ( https://tomelliott.com/jquery/twitter-feed-authentication-search/)?

    • Tom Elliott says:

      Hi John, thanks for your comment. I’ve made a few updates to the search tutorial to bring it more up-to-date with the original (static) jQuery twitter feed so the steps in this post also apply to the search. I’ve also added a fade demo for search which will hopefully help 🙂

  • Luke says:

    Hi Tom,

    Excellent as usual, how can i display two tweets and fade them both?

    • Tom Elliott says:

      Hi Luke, thanks! Good question *scratch head*…it would probably need a few mods and I’d start by setting starttweet to 2 in the animate function and perhaps calling fadetweet(); function twice…

      • Luke says:

        Hi tom here is how i did it,

        CSS – Create a container and hide the overflow (hiding tweets you don’t want)

        #twitter-feed{
        border: 1px solid black;
        height: 100px;
        overflow: hidden;
        width: 500px;
        float: left;
        }

        .twitter-article {

        float: left;
        width: 200px;
        border: 1px solid red;
        height: 100px;
        margin-left: 40px;

        HTML/ELEMENTS (this is generated by toms javascript file, you only div div id=”twitter-feed”)

        Tweet 1
        Tweet 2
        Tweet 3
        Tweet 4
        Tweet 5
        Tweet 6

        The JS put the function at the top of the file,

        function fadeOut(elements, callback)
        {
        if (elements.length){
        elements.eq(0).addClass(‘fade’);
        elements.eq(0).delay( 5000 ).fadeOut(3000, function(){
        $(‘.fade’).appendTo(‘#twitter-feed’);
        $(‘.fade’).css(‘display’, ‘block’);
        $(‘.fade’).removeClass(‘fade’);
        fadeOut(elements.slice(1 ,1), callback);
        });
        }
        else {
        callback();
        }
        }

        then put this above window.load

        setTimeout(function(){

        //$(function(){
        //fadeOut($(‘#twitter-feed div’), function(){
        // alert(“done”);
        // slideuptwitter();

        function infinite(){
        fadeOut($(‘#twitter-feed div’), function(){
        //fadeIn($(‘#twitter-feed div’), function(){
        infinite();
        //});
        });
        }
        $(function(){
        infinite();
        });

        }, 6000);

        You can see it in action on

        http://jsfiddle.net/7TQCr/7/

        Thanks for everything Tom, i may go on to build a tweet slider yet, but i’m happy at the moment

  • Jonathan says:

    Hi Tom,

    This is excellent. I can’t wait to see how you are going to implement the carousel. Will it continuously scroll and update without having to refresh/clear the page?

    I want to show the latest x tweets (say 15) on my website. New tweets would appear at the top or bottom of the list (depending on the direction of scroll). If there were no new tweets the 15th item would appear again so the scroll was endless, however older tweets would be pushed off the list when a new tweet/s arrived.

    Does that sound possible?

  • Jonathan says:

    Thanks for sharing. Its looking good.

    I’ve found some code to do scrolling with un-ordered lists and was wondering if I could cache my twitter feed into a mysql database first (so it could be moderated) and then pull the “approved” tweets from a second table into a and then do and ajax append / remove to update the list so there is only the 15 or so entries that I want.

    It all works perfectly in my head, but I’m stumbling my way through all of this having never done any php/JS programming before. Finding others code and pulling it apart and mashing it up seems to be the best way for me to learn at the moment, and tutorials like your are fab!

    • Tom Elliott says:

      Hi Jonathan, thanks – yeah I see what you’re trying to do. I’d start with a scheduled PHP script that does all the authentication, checking for new tweets and if a new one exists, insert it to the database. On the other end, you’d have your feed with the PHP file but instead of running the authentication, the PHP file would pull out the approved tweets from the DB.

      Code mashing is always a good way to learn 😉

  • Stumac says:

    Set up as per your fade demo with Twitter details changed.

    Hangs with no Tweets loading – line 149 twitterfeed-fade.js reporting error as

    ReferenceError: Can’t find variable: exception

    My knowledge of javascript is so small ….. Appreciate some help!
    Thank you

    • Tom Elliott says:

      Hi Stumac, looking at your link, I cannot open the get tweets php file – it tries to download instead. Check your server/setup and make sure you can run the PHP and that tweets are displaying as JSON output

      • Stumac says:

        Awaiting answer from server techies regarding their set up.
        In the mean time have moved to my server where php is definitely running, confirmed by phpinfo, but still get same error on line 149

        • Tom Elliott says:

          Hi Stumac, looking at your get tweets PHP file, there’s a syntax error – within the PHP, this will be causing your exception is not defined problem.

          • Stumac says:

            Thanks Tom – looking at again notice the consumer key etc incorrect! Sometime it’s staring you ……..!

            Waiting to hear back from Plusnet re client’s issue – could be a while!

  • Tolu says:

    thanks so much for this tutorial, however, i’m having error 500 on my wordpress site, what could be causing it?

  • Tolu says:

    Thanks again for a very helpful tutorial. How do I make the tweets scroll from right to left instead of scrolling up. Thanks again.

    • Tom Elliott says:

      Hey Tolu, to get the tweets to fade in and out horizontally instead of vertically I would try using margin-left instead of margin-top. I haven’t tried this though but that’s where I’d start 🙂

  • Jonathan says:

    Hi Tom,

    So I found some useful scrips at 140dev.com and have managed to get my twitter feed into mysql. I’ve written a filmmaker front end to deal with the moderation, but am really struggling with getting the data to update in real time and scroll. I can pull the individual records ok. Have you got any suggestions of what I should be googling – i’ve exhausted the search terms I could think of!

    • Tom Elliott says:

      Hi Jonathan, yeah it’s quite a niche thing I think you’re trying to do here and quite tricky so Google might well turn up empty. I would start by calling the main twitter generation function based on an interval time which checks the latest tweet from the database compared to the last tweet in the feed. If the tweet is different, then add it to the last item in the feed. This is something I would like to implement within my Tweet Carousel but not straightforward and haven’t got round to it yet :S

  • Jeroen Beeksma says:

    Hi Tom i’ve a question. i’m not know with the JSOn stuff. what is do know is that i’ve to fill in a token or something like that. could you give me advice what to do?

  • belle says:

    Hi Tom,
    Great Tutorial but I’m having a problem with my tweets. I’m not sure what I’m doing wrong. It keeps saying that I have ‘Requested page not found. [404]’ or ‘Connection problem. Check file path and www vs non-www in getJSON request’. I tried to fix by removing the ‘www’ didn’t fix it. My ‘get-tweets1.1.php’ seems to be loading the tweets just fine. But the error message will still show. Please can you have a look and help me.

    • Tom Elliott says:

      Hi Belle, thanks – yes that error can be a number of issues (the ‘www’ being the most common but you’ve checked that). If you can send me a link I’m happy to take a look

  • James says:

    Hey Tom – I’ve implemented this successfully to just show a single line of text (just the tweet and the @name), but I can’t for the life of me get the text to cut off at a certain amount of letters and append a ‘…’
    I know how to do it but I don’t have a good enough understanding of how your code works to implement it.
    Thanks in advance, keep up the good work 🙂

    • Tom Elliott says:

      Hi James, yeah you’ll want to add something like
      status = status.substr(0, X) + '...';
      where X is the number of characters to cut off at and drop it before before the lines:
      if (showtweetlinks == true) {
      status = addlinks(status);
      }

      Hope that helps 🙂

      • James says:

        Hey, thanks.
        I ended up going with something a bit more complex, because I wanted it to cut off at the end of a word, as well as only display the ‘…’ if the length was too long and needed to be cut. For anyone potentially wanting to do the same:

        var twitstatus = feeds[i].text;
        var maxLength = 95;
        var trimmedString = twitstatus.substr(0, maxLength);
        if (twitstatus.length > maxLength) {
        var status = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(” “)))+’…’;
        } else {
        var status = twitstatus;
        }

        Thanks for your help 🙂

  • Tom Elliott says:

    Hi RM, no problem – it looks like the username your tweets PHP file only has one tweet and it’s a direct tweet so won’t show up since showdirecttweets is set to false.

    • RM Informáticos says:

      Works!!!! i set showdirectweets to true, and show the tweet (at this moment only have 1)

      Thanks a lot Tom.

  • Javier says:

    Hi, thanks a lot for this tutorial, it works ok for me.
    My question: is there a chance to change the language that the dates of the tweets are displayed? Thanks.

  • Caglar says:

    Thanks for this excellent tutorial.

    I am having an error but I couldn’t find the reason. Can you guide me?

    Uncaught TypeError: Object # has no method ‘error’

    • Caglar says:

      I used another jquery library and now my error is

      Uncaught ReferenceError: exception is not defined

      Any idea?

      • Caglar says:

        OK, I could solve the problem by comenting the session_start. Therefore, it didn’t enter into the exception variable and it is working 🙂

  • Mike says:

    Hello tom i have a question, i have this twitter feed working fine on a static html page, but when i add it to my php game site script i cant seem to get it to work.
    i know all the js and div calls are there when i view the source code of the php generated html page.
    When i add twitters wiget it works fine, but i dont want that one.
    I was woundering if there are any code tricks to make this work in a html page generated by php script?

    • Tom Elliott says:

      Hi Mike, just taken a look at the Twitter feed and you seem to have it working now 🙂

      • Mike says:

        Hello Tom, yes that twitter widget you seen on my site was “twitters widget” that i left there untill i can get the “fade rotation” one to work on there.
        Twitters seems to be flash and is bothering the flash games when it updates while playing a game.
        Im thinking is there a way to call it up to a spot on the left of the site with “JS” after the site loads? sort of a delayed opening so all the all the other stuff loads and the the widget loads last?

  • Carlos says:

    Hi Tom. Thank you for this plugin. I have the tweets in JSON format but no luck printing them on my page. I’m using foundation 5. Do you know if this is can cause problems?

    I currently have no errors, so don’t even know where to turn, and I was able to get this working on a different site without any issues. Really stuck.

    Thanks for your help.

    C

    Thanks again. C

  • nuli says:

    my username-twet.txt has appeared
    what else i have to do?

  • nicole says:

    Hi Tom,
    Great tutorial. I have 2 different twitter accounts that I want to show tweets from. One account will show in the footer (which is working fine) and the other account I want in a sidebar on the same page (which is not working) When I put the sidebar twitter fade up, the footer stops working. When I remove it, it starts back working. I know I’m doing something wrong, just can’t figure out what. Can you help?

    • Tom Elliott says:

      Hi Nicole, I’ll try and take a look if you want to send me a link. I’ve seen people use multiple feeds on one page and I think the easiest thing to do would be to have separate PHP and JavaScript files (and make sure to rename the DIVs!) 🙂

      • Tom Elliott says:

        Hi Nicole, just taken a look. The twitter-feed file twitterfeed-fade.js only references the first twitter feed… easiest thing in this case would be to just replicate this file and change the path the PHP for your second feed and the update occurances of $('#twitter-feed') to $('#twitter-feed1'). Hope that helps :)

        • nicole says:

          Hi Tom,
          Okay, I did add the path for the second feed, but now it’s saying internal server error 500.

          • Tom Elliott says:

            Hi Nicole, yeah both PHP files aren’t rendering any tweets now… have you changed anything? Hard to see what’s going on as there’s no errors but try checking your logs or turning PHP error reporting on your server for clues.

        • Nicole says:

          Hi Tom, thanks for taking a look. I fixed it to were it’s not getting the error. The bottom tweets move 1 time and the sidebar tweets move continuously, but after a few rotations it starts tweeting 2 at a time. I’m not sure what I’m doing wrong.

          • Tom Elliott says:

            Hi Nicole, hmm – I don’t think you’re doing anything wrong… it’s just that the animated Twitter feed wasn’t initially designed to work with another feed. I think what’s happening is the variables from both functions are getting mixed up as the vars are scoped globally. You could try enclosing everything after the opening document.ready function within another function e.g. $(function() { and }); – hope that helps! 🙂

  • Tom Elliott says:

    Hi Andrew, yes the fatal error in the PHP needs to be fixed… looks like the get tweets php on the goodintoday domain is looking at the files on the other domain? I would make sure the OAuth files are relative to the twitter file in both domains.

    I haven’t user Twitter API to get a list of tweets from people you follow in addition to the authenticating user but you might want to check out the GET statuses/home_timeline… you may just be able to replace ‘user_timeline.json’ with ‘home_timeline.json’ in your PHP connection string. 🙂

  • Andrew says:

    Okay, with the help of my tech support I got the directory thing corrected. The issue was with the way I was calling for the get-tweets file in the twitterfeed-fade.js. Evidently calling it by the http address was causing the conflict. Changed to local directories, as it’s a local file request, and it works fine. The second part of my previous post comment still stands however. I’d like to know how to adjust the code to filter the results to show the people I follow as well as my own tweets? Kind of like a news ticker type thing only Twitter style. Thanks for the awesomeness! 🙂

  • Ed says:

    Hi Tom. Great Tutorial. I was wondering, what would be the best way to insert a controller that could call up previous or next tweets. I’m kinda thinking a jquery call on the “#tw…” elements but just wanted to get your input before I spend a few hours plucking code.

    Thanks,Ed

    • Tom Elliott says:

      Hi Ed, yeah you should be able to run the fadetweet function when either next or previous is pressed, except when previous is pressed you would need to decrement the animatetweet variable instead of animatetweet++

  • Ekrem says:

    Hi Tom. Thank you for this tutorial. It was very useful for me. Can you, please, tell me how to show two tweets for once (for one fade). Thank you in advance

  • Larry B. says:

    Hello Tom , I appreciate the great integrated JSON/PHP solution.
    My twitter window only displays the username without any of the related tweets. We don’t experience any errors. I would appreciate any suggestions.
    Thanks

  • James says:

    Hey Tom,

    I’m trying to merge 2 of your posts, the twitter search and the fade rotation, you can see the results here: http://www.jgsys.co.uk/testing

    I seem to be stuck with the javascript – which I must say I am a complete novice at, I’ve gotten both to work on their own without an issue so I know it’s not a twitteroauth issue or get-tweets.php issue, it’s purely the js but I can figure out what I’m missing.

    Any pointers?

  • Andy says:

    Hi – I’m putting this into the footer on my pages – but when I ciick QUICKLY between pages (before the first page has finished loading) – I get an error flash up saying:

    error: Connection problem. Check file path and www vs non-www in getJSON request

    Any ideas?
    Thank!
    Andy

    • Tom Elliott says:

      Hi Andy,
      I added an alert on error to help people debug any issues but quickly refreshing or changing the page before it’s loaded also triggers the alert. If the feed works normally, you can remove the alert from the end of .error() function 🙂

  • Tom Elliott says:

    Hi Deanna,
    It looks like your JavaScript isn’t pointing to the PHP with the JSON encoded set of tweets

  • Guy Alexis says:

    I’m trying to implement it on my website. But i have an error = ‘Requested JSON parse failed.’;

    How can i solve it and where am i suppose to put the JavaScript code above?

    Thanks

  • Nathalie says:

    Soooooo frustrated! I’ve done everything you said (and I very much thank you for all of the GOOD explanation you’re giving!) but the tweets aren’t showing up !

    All relative paths are well set. All tokens from twitter app are well set. Path to library is set yet, it’s not showing tweets, nor is it showing errors. Grrrrr what is going on ? 🙁

    • Tom Elliott says:

      Hi Nathalie, is the PHP file showing tweets? If you’re getting just a blank screen on the PHP, try checking the error log files or turn on the display of PHP errors as this can be for a number of reasons. If you send me a link, I’ll try and take a look

  • Adrian Robison says:

    Hi there, I can’t seem to make my Twitter feed work. I got it to work before, but YouTube changed it’s API. Now when I paste the code after the YouTube Javascript, the video doesn’t play. If I paste it before, the Twitter feed doesn’t work.

    On the one that doesn’t work, there is an error icon in it’s place. (It is located on the bottom of the page, to the left of the “Booking | Site by: Adrian Robison”). It used to work fine, before YouTube changed their API. After YouTube changed their API, posting before the YouTube JS code resulted in the small error icon and posting after the YouTube JS code resulted in the YouTube player not working at all (pure grey screen, unusable video site, loss of entire footer). Perhaps the JS code is shared in some way, making each others code incompatible?

    Here is the YouTube JS code in question:

    var hap_player;
    jQuery(document).ready(function($) {
    var apvb_settings = {
    /* mediaId: unique string for player identification (if multiple player instances were used, then strings need to be different!) */
    mediaId:’player1′,
    /* componentFixedSize: true/false. Responsive = false, fixed = true */
    componentFixedSize: false,
    /*defaultVolume: 0-1 */
    defaultVolume:1,
    /*autoPlay: true/false (default false on mobile) */
    autoPlay:true,
    /*randomPlay: true/false */
    randomPlay:false,
    /* loopingOn: on playlist end rewind to beginning (last item in playlist) */
    loopingOn: true,
    /* defaultGallerySide: bottom / right (default thumbnail side) */
    defaultGallerySide: ‘bottom’,
    /* scrollType: buttons / scroll */
    scrollType: ‘scroll’,
    /* autoOpenPlaylist: true/false. Auto open playlist on beginning */
    autoOpenPlaylist: false,
    /* closePlaylistOnVideoSelect: close playlist on video select */
    closePlaylistOnVideoSelect: false,
    /* onPlaylistEndGoToUrl: true/false, navigate to url on playlist end (last item in playlist). Note: this will override loopingOn! */
    onPlaylistEndGoToUrl: false,
    /* onPlaylistEndUrl: url to redirect to */
    onPlaylistEndUrl: ‘http://www.google.com/’,
    /* onPlaylistEndTarget: _blank (open in new window) / _parent (open in same window) */
    onPlaylistEndTarget: ‘_parent’,
    /*useCookieDetection; use detection with local storage/cookies of skipping intro if already visited (true/false). ‘onPlaylistEndGoToUrl’ must be ‘true’ for this to happen. */
    useCookieDetection: false,
    /* useKeyboardNavigation: true/false (left arrow=previous media, right arrow=next media, space=pause/play, m=mute/unmute) */
    useKeyboardNavigation: false,
    ytAppId:’YOUTUBE API KEY HERE’,/* youtube api key */

    /* DEEPLINKING SETTINGS */
    /* useDeeplink: true, false */
    useDeeplink:false,
    /* startUrl: deeplink start url, enter ‘ul’ data-address/’li’ data-address (two levels). Or just ‘ul’ data-address (single level). */
    startUrl: ‘playlist3/youtube_playlist1’,

    /* NO DEEPLINKING SETTINGS */
    /*activePlaylist: enter element ‘id’ attributte */
    activePlaylist:’playlist3′
    };
    //init component
    hap_player = $(‘#componentWrapper’).apvb(apvb_settings);
    });

    • Tom Elliott says:

      Hi Adrian, after having a quick look, there’s a JS error:
      Uncaught TypeError: $ is not a function in the Twitter Feed JS

      Perhaps by either changing the beginning of the YouTube code to
      $(document).ready(function () {

      Or the beginning of the twitter-feed js to
      jQuery(document).ready(function ($) {

      Might fix it

      Hope that helps 🙂

      • Adrian Robison says:

        Thanks so much! Changing the top of the code on twitterfeed-fade.js to
        jQuery(document).ready(function ($) { ended up solving all of my problems.

        Thanks again!
        -Adrian

        PS: For anyone else having the same problem, make sure you are changing twitterfeed-fade.js and not twitterfeed.js!

  • Eliud says:

    How do I implement this in a joomla 3 based website?

  • Heather says:

    Hi, Great tutorial. I need to be able to display any embedded images as wel as the tweet – is this possible?

  • Kenneth Smith says:

    Albeit a little difficult to follow over a few blogs, from the Auth, to basic scrolling feed to the fading one, then viewing page source to get the files for each of, got there in the end.

    Great series of blogs, gave me just what i needed mate.

    Cheers

  • sonia says:

    Hello,

    Thanks a lot for this tutorial, it’s perfect!
    I’ve a question, I would like to show a picture in the box (ans not just a link). Is it possible ?

    Thanks,
    Sonia (from France)

  • Valter says:

    Hello, great script!!!
    I have a question, is it possible to have all “twitter-text” linked to open the real twitter page?
    An example I have edited the script so not to show the “https://t.co/xyz” in “Go to tweet” in this way:

    return ‘GO to tweet…‘;

    BUT if I want that ALL “twitter-text” linked to “+url+” how can i do it?

    Thank you.