auto switch class within li

by rupesx

HTML

<div id="tabs">
  <li class="on">tab1</li>
  <li>tab2</li>
  <li>tab3</li>
</div>

CSS

.on{
  color: red;
}

JavaScript

//cache a reference to the tabs
var tabContainer = $('#tabs');
var tabs = $('#tabs li');

//on click to tab, turn it on, and turn previously-on tab off
tabs.click(function() {
    $(this).addClass('on').siblings('.on').removeClass('on');
});

//auto-rotate every 5 seconds
var slideInterval;

function initiateSlideInterval() {
    slideInterval = setInterval(function() {

        //get currently-on tab
        var onTab = tabs.filter('.on');

        //click either next tab, if exists, else first one
        var nextTab = onTab.index() < tabs.length - 1 ? onTab.next() : tabs.first();
        nextTab.click();
    }, 1000);

}
initiateSlideInterval();

tabContainer.mouseover(function() {
    clearInterval(slideInterval)
});
tabContainer.mouseout(function() {
    initiateSlideInterval();
});