Creating Rotating Tabs using jQuery

Some time ago I wrote an article about creating some tabs using jQuery, the Javascript library. One of the readers asked if I could devise a way to “add a code that will automatically and continuosly go to the next tab even without clicking on the tabs?”. Well, here it is. In addition to the rotating tabs, we also need to take care of the behaviour when the user actually clicks on a tab by stopping the cycling behaviour on the desired tab. Finally, we will also highlight the selected tab both in the cycling mode and when the user clicks on a tab.

There’s a new version of this article: Multiple Rotating jQuery Tabs. featuring automatic rotation of the tabs, highlighting of the selected tab title and supports multiple tab panels.

You might want to have a look at the rotating jQuery tabs first. Every second, the current tab fades out and the next one fades in. Click on a tab title and it will display that tab stopping the cycling. After initializing some variables, we will define one function that will be used for changing the tabs and highlight the title. This function will be called by the CLICK event and also from the cycling or rotating system. For the selection, I used a technique from a previous article about jQuery selection and revealing. Whenever a new tab is displayed, we will remove the .select class from the other tabs and apply to to the current one, thus highlighting the title of the current tab.

//array to store IDs of our tabs
var tabs = [];
//index for array
var ind = 0;
//store setInterval reference
var inter;

//change tab and highlight current tab title
function change(stringref){
  //hide the other tabs
  jQuery('.tab:not(#' + stringref + ')').hide();
  //show proper tab, catch IE6 bug
  if (jQuery.browser.msie && jQuery.browser.version.substr(0,3) == "6.0")
    jQuery('.tab#' + stringref).show();
  else
    jQuery('.tab#' + stringref).fadeIn();
  //clear highlight from previous tab title
  jQuery('.htabs a:not(#' + stringref + 't)').removeClass('select');
  //highlight current tab title
  jQuery('.htabs a[href=#' + stringref + ']').addClass('select');
}

The next function will be called at a regular interval and it’s what will fade out the previous tab and fade in the next tab.

function next(){
  //call change to display next tab
  change(tabs[ind++]);
  //if it's the last tab, clear the index
  if(ind >= tabs.length)
  ind = 0;
}

Now, the following block is the first thing that will be executed when the page is ready. We need to store a reference to all of our tabs in an array to iterate it. We will use the map function from jQuery to walk through the elements: each time we found a new element, we will store its reference into an array. After the map iteration, the ind variable, the array index, is set to 1 so when change is called, the number used will be 1, thus displaying the next tab. If it was 0 the next element displayed would have been the same tab.

jQuery(document).ready(function(){
  //store all tabs in array
  jQuery('.tab').map(function(){
    tabs[ind++] = jQuery(this).attr('id');
  })
  //set index to next element to fade
  ind = 1;
  //initialize tabs, display the current tab
  jQuery('.tab:not(:first)').hide();
  jQuery('.tab:first').show();
  //highlight the current tab title
  jQuery('#' + tabs[0] + 't').addClass('select');

The following snippet contains the behavioural logic. If we click on a tab title, we will clear the rotating behaviour by clearing the reference to the interval we have defined, inter (this is defined in the last lines of the code). We will store the reference in a variable stringref and call change. The last two lines set the next function to be repeated at an interval of 1000 (merely for testing purposes), which is one second, so if you want to rotate the tabs every 4 seconds you should add 4000. The setInterval function returns a reference that we will be storing and is the one we used to clear the interval when the user clicks on a tab.

//handler for clicking on tabs
jQuery('.htabs a').click(function(){
  //if tab is clicked, stop rotating
  clearInterval(inter); //store reference to clicked tab
  stringref = jQuery(this).attr('href').split('#')[1];
  //display referenced tab
  change(stringref);
  return false;
});
//start rotating tabs
inter = setInterval('next()', 1000);
});

As you can see in the example  for the tabs, the XHTML structure is made of simple lists with their matching IDs to be captured by the JavaScript. Make sure your CSS contains the proper .select class definition. The markup is the same than the previous jQuery tabs article, and just like it, the css is not an integral part of it. Despite the fact that we need the .select class to highlight the tab, we could have just applied an style attribute. Finally, if you don’t want tabs to rotate, just remove the setInterval sentence. Remove also the next function and clearInterval. You are welcome to download the code below but also take a look at the updated version:

WordPress plugin now available!

You can now purchase on CodeCanyon a widget for WordPress based in the latest version of this code: Rotating Tabs Widget for WordPress to displays your latest posts from categories or tags using the rotating tabs.


“Creating Rotating Tabs using jQuery” received 38 comments! Add yours.

  1. Lawrence December 8th, 2009

    Hey! Thanks for this! :) Im gonna spread the love!

  2. rana December 9th, 2009

    nice tutorial…

  3. MIka December 9th, 2009

    Amazing site. :) I love it, especially the typography posts. (I’m not the most expressive person around so forgive me if this sounds so bland)

    A link just led me here and I wounded up reading all of your posts.

    Great stuff. Looking forward to more.

    Love, Mika.

  4. krishna December 9th, 2009

    Hi nice article.

  5. Elliot December 9th, 2009

    Thanks Mika, I’ve a foot on several disciplines so I try to put a bit of everything here without loosing consistency. I’m into toy art now so I will post something more about it soon.

  6. Jenna Molby December 9th, 2009

    Great article, thank you!

  7. Creating Rotating Tabs using jQuery December 10th, 2009

    [...] Visit Source. [...]

  8. Alex Flueras December 11th, 2009

    Nice little piece of coding. Thanks for sharing.

  9. Elliot December 12th, 2009

    Thanks Alex, your design work is quite good.

  10. Thanh December 29th, 2009

    Very nice piece of work. One thing, is it possible to create multiple instances of the script on a single page? I have to create a new JS file for each instance. Any thoughts? Otherwise, very nice work!

  11. Phil January 5th, 2010

    How can i stop the page from jumping to the top each time a tab rotates?

  12. Behind the Scenes at Vibrant and Inspiring Design Blog ilovecolors | Inside the Webb January 28th, 2010

    [...] popular are the articles about some interface elements tutorials using the jQuery library, like rotating tabs, sliding menus or rollovers and [...]

  13. Asdeaq March 16th, 2010

    ilovethiswebsite…

  14. Steve June 22nd, 2010

    This is exactly what i was looking for. I already have the Jquery tabs installed, but i wanted the rotate effect. Will give it a try tommorow to see how it works. Thanks for sharing!

  15. Steve Again June 23rd, 2010

    Hi again, Don’t know if you still follow this. I have successfully used the tabs, only thing i can’t get it working is the .select class. Looking at the instructions, you say that ‘Despite the fact that we need the .select class to highlight the tab, we could have just applied an style attribute.’
    Can you give me some more details about it so i can try this?
    Thanks a lot for a great tut!

  16. Elio June 23rd, 2010

    Hi Steve, it means that css is not an integral part of the script, because you could add
    jQuery(“obj”).css(“style”, “someHighlighting”);
    to achieve the same goal.
    What is the issue you’re experimenting with selection?

  17. Steve June 23rd, 2010

    Elio, thanks for replying!
    The tabs work great, they rotate, the hover works too, only the .select class is not recognised. When i view the source in Firebug, the .select class is marked with a line-through. I have tried the following in css:
    .select{
    color: #d00;
    }

    and
    .htabs .select a span{
    color: #7AA9DD;
    }
    but it will not highlight the selected tab.
    The website is http://lemy.co.uk
    Thanks for any pointers you may have for this!

  18. Elio June 24th, 2010

    Steve, I’ve been inspecting your markup. From your script, is it possible that you’re applying an .active class instead of a .select class? if that’s so, I couldn’t find a CSS rule for .active. The rule should be .active{color: #d00} for jQuery to recognize it as a class. Writing .htabs .select a span won’t do it. Try writing an .active class as referenced by your script and let me know.

  19. Steve June 24th, 2010

    Thanks for that Eliot!
    I was trying to change the class name in the css and the jscript. I have tried both ways, with .active defined in the css and the script + the original .select class name.
    It’s now named as .select exactly like in the jscript and still no select effect.
    Do you have other suggestion for me to try?
    Thanks a lot for the support so far!

  20. Steve June 25th, 2010

    Well the good news is that i got it to work by using .htabs .myclass { color: #7AA9DD;}
    The bad news is the first tab does not appear selected from start(not the end of the world) and also in internet explorer 6 things don’t look so good – .myclass not working + a small space at the right of the unordered list. Still have some tweaking ahead of me.

  21. Elio June 25th, 2010

    Steve, I’m glad to hear that you almost got it. Perhaps (if you have the time of course), you might want to download the working example and start building your own solution using it.

  22. techflaps - Waves of Technology | 34 Excellent Tutorials About How To Create And Use jQuery Tabs June 29th, 2010

    [...] ROTATING JQUERY TABS [...]

  23. Gareth July 6th, 2010

    If you have a long page (vertically) and scroll down beyond the tab banner, everytime the tab changes it automatically scrolls to the top of the page. Not allowing users to browse beyond the top of the page.

    Any fixes?

  24. Elio July 8th, 2010

    Humm you’re right. Even though
    return false;
    is added in the click function the browser jumps towards the anchor.
    The solution is simpler than it looks. Move the following lines:
    //hide the other tabs
    jQuery('.tab:not(#' + stringref + ')').hide();

    from the start of the change function to the end of it, just before the closing }
    That should do it.

  25. Gareth July 8th, 2010

    Thanks Elio, much appreciated. That worked but now it doesn’t highlight the tabs i.e. it doesn’t give the ‘select’ class when active.

  26. Elio July 8th, 2010

    Gareth, please double check it. I’ve tested it when I posted the fix and tested it just now (downloading and modifying the file available for download on this page) and both highlighting and content displaying works fine.

  27. Jilles July 16th, 2010

    Great code! Only one issue. When clicking on a button the rotating stops. That is cool, but after leaving the “button” the tabs doesn’t start rotating again. Any solution for that?

  28. Elio July 16th, 2010

    Hummm that’s is not an issue because there is no such thing as “leaving the button”, how would you do that?
    What you could do is to add another button and issue this call again

    inter = setInterval("next()", 1000);

    Or, when the button is clicked you could start a timer timing out after a veeery long time allowing the user to explore the tab content. After it times out, tabs start rotating again.
    However, it’s not a practical solution and I think there are more trouble doing it so than just stopping the rotation, allowing the user to explore the content of each tab at its own pace.

  29. Jimmy December 3rd, 2010

    Script is great, Do you know why on some browser the first tabs loads, and all other tabs are blank. But on other browser all is working fine.

  30. Gerry Straathof December 12th, 2010

    Thanks for this! I used something like this to build a menu for a web-based publishing engine that works on desktops or the iPad. Once you understand the basics of a Tab system, you can expand on it quite a lot. Http://www.straathof.acadnet.ca/beta8.7.2

  31. Larry April 28th, 2011

    I can get this to highlight text as it moves along the slider, but when I try to use a box built in css to highlight it doesn’t work. Anyone been able to highlight a tab box as the slider moves along?

  32. paul July 5th, 2011

    This is awsome, just what i needed, my js isnt as good as my php so a helping hand was much appreciated.

    The one thing I wanted was to add a longer delay when the user hovers over the section, so they have properly read / click stuff, so I added the following inplace of the inter = setInterval(“next()”, 1000);

    var delay = 10000;

    $(‘.tabs’).hover(function(){
    clearInterval(inter);
    inter = setInterval(“next()”, 1000000);
    }, function(){
    clearInterval(inter);
    inter = setInterval(“next()”, delay);
    });

    inter = setInterval(“next()”, delay);

  33. shortcodes 4 | wordpress September 10th, 2011

    [...] Creating Rotating Tabs using jQueryНекоторое время назад я написал статью о создании некоторые вкладки использованием JQuery, библиотеки JavaScript. Один из читателей спросил, могу ли я найти способ, чтобы “добавить программу, которая автоматически и непрерывно перейти к следующей вкладке даже не нажимая на вкладки?”. Ну, вот оно и есть. В дополнение к вращающимся вкладок, мы также должны заботиться о поведении, когда пользователь нажимает на самом деле вкладки, останавливая велосипедные поведения на нужную вкладку. Наконец, мы также выделить выбранной вкладки, как в режиме езда на велосипеде, а когда пользователь щелкает по закладке. Эта запись была опубликована в рубрике shortcodes и отмечена метками shortcodes пользователем gogadmin. Добавить в закладки ссылку. [...]

  34. Ravindra November 16th, 2011

    Awesome use of scrolling tabs with jquery…thanks.

  35. Richard Bultitude January 25th, 2012

    Great script and really helpful explanation. The only thing I don’t understand in the script why a ‘t’ is being looked for when clearing or adding the highlight. Can you please shed some light on this logic?
    Thanks :]

  36. stoły bilardowe October 31st, 2012

    hey there and thank you for your info – I’ve certainly picked up something new from right here. I did however expertise a few technical issues using this web site, since I experienced to reload the site a lot of times previous to I could get it to load properly. I had been wondering if your hosting is OK? Not that I’m complaining, but
    sluggish loading instances times will sometimes affect your placement in
    google and could damage your high-quality score if advertising and
    marketing with Adwords. Anyway I’m adding this RSS to my e-mail and can look out for a lot more of your respective interesting content. Make sure you update this again soon.

  37. Daniel Lemes February 10th, 2013

    4 years and still great. Thanks!

  38. Behind the Scenes at Vibrant and Inspiring Design Blog ilovecolors | Ian Carnaghan March 10th, 2013

    [...] popular are the articles about some interface elements tutorials using the jQuery library, like rotating tabs, sliding menus or rollovers and [...]

Leave a comment