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.

[js]
//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’);
}
[/js]

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.

[js]
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;
}
[/js]

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.

[js]
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’);
[/js]

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.

[js]
//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);
});
[/js]

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:

37 thoughts on “Creating Rotating Tabs using jQuery”

  1. 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.

  2. 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.

  3. 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!

  4. 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!

  5. 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!

  6. 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?

  7. 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!

    1. 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.

  8. 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!

  9. 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.

  10. 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?

    1. 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.

  11. 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.

  12. 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.

  13. 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?

  14. 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.

  15. 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.

  16. 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?

  17. 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);

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

  19. 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 :]

Leave a Reply to Jenna Molby Cancel reply