Automatic tab switcher in javascript or jquery
I built a custom tab system (4 tabs) with jquery. It works manually, but I want it to run automatically, i.e. every 5 seconds. I can launch each tab with one click, but I donβt know how to go back to the beginning from the first tab once it reaches the last tab.
The coding is too long to go through here, so I made a jsfiddle link for it: http://jsfiddle.net/ZSPX3/
I just want to loop over each tab and click on each one and then start over from the beginning of the tab again as I want an endless slideshow. But I'm stuck ...
I don't need plugins, I want to learn how to do it with my own hand, please.
Many thanks
source to share
The key part here is to check the index of the Currently tab and see if there are any tabs there. If not, go back to the first tab. So:
Html
<ul id='tabs'>
<li class='on'>tab 1</li>
<li>tab 2</li>
<li>tab 3</li>
<li>tab 4</li>
<li>tab 5</li>
</ul>
CSS
#tabs { list-style: none; margin: 0; padding: 0; }
#tabs li { float: left; background: #ddd; padding: 6px; }
#tabs li.on { background: #f90; color: #fff; }
JS (assumes jQuery)
$(function() {
//cache a reference to the 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
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();
}, 5000);
});
We compare the index with the zero index of the tab at the current moment with the total number of tabs (-1, to account for zero indexing). If the former is less than the latter, there are still tabs; if not, that is, they are equal, we have reached the end - let's go back to the beginning.
Hope it helps.
Here's the code you can use:
JQuery
setInterval(function() {
var current = parseInt($('li.selected a').data('links-to').split('_')[1],10);
var idx=current-1;
var max = $('.carouselLinks li a').length;
idx = (current<max) ? (idx+1):0;
$('a:eq('+idx+')').trigger('click');
}, 3000);
Updated jsFiddle example .
source to share