I am looking to have the Twitter Bootstrap tabs change on a timed sequence. I am using them kind of like a carousel. I would like the tabs to change to the next one every 10 seconds.
Here is an example: http://library.buffalo.edu
Click on the news stories to see what I mean. Any help would be appreciated.
Fixed the AppSol solution:
// Tab-Pane change function
var tabChange = function(){
var tabs = $('.nav-tabs > li');
var active = tabs.filter('.active');
var next = active.next('li').length? active.next('li').find('a') : tabs.filter(':first-child').find('a');
// Use the Bootsrap tab show method
next.tab('show')
}
// Tab Cycle function
var tabCycle = setInterval(tabChange, 5000)
// Tab click event handler
$(function(){
$('.nav-tabs a').click(function(e) {
e.preventDefault();
// Stop the cycle
clearInterval(tabCycle);
// Show the clicked tabs associated tab-pane
$(this).tab('show')
// Start the cycle again in a predefined amount of time
setTimeout(function(){
tabCycle = setInterval(tabChange, 5000)
}, 30000);
});
});
Something like this will create a never-ending carousel loop; it will cycle through all tabs and return to the first one after it reaches the last (change #yourTabWrapper
to be an appropriate selector for whatever contains your tab markup):
var tabCarousel = setInterval(function() {
var tabs = $('#yourTabWrapper .nav-tabs > li'),
active = tabs.filter('.active'),
next = active.next('li'),
toClick = next.length ? next.find('a') : tabs.eq(0).find('a');
toClick.trigger('click');
}, 3000);
All we're doing is finding the active tab, then triggering the click
event on the next tab in the list. If there is no next tab, we trigger the click
event on the first tab. Note that the event is actually triggered on the a
, not the li
.
Now, if you want to add logic to pause or reset the interval when the user either hovers over or manually clicks a tab, that will need to be added separately, and you would use clearInterval(tabCarousel)
to stop the cycling.
Here is a basic demo:
--- jsFiddle DEMO ---
Another nice option is to pause the slideshow when a tab is clicked:
// Tab-Pane change function
var tabChange = function(){
var tabs = $('.nav-tabs > li');
var active = tabs.filter('.active');
var next = active.next('li').length? active.next('li').find('a') : tabs.filter(':first-child').find('a');
// Use the Bootsrap tab show method
next.tab('show')
}
// Tab Cycle function
var tabCycle = setInterval(tabChange, 5000)
// Tab click event handler
$(this).find('.nav-tabs a').click(function(e) {
e.preventDefault();
// Stop the cycle
clearInterval(tabCycle);
// Show the clicked tabs associated tab-pane
$(this).tab('show')
// Start the cycle again in a predefined amount of time
setTimeout(function(){
tabCycle = setInterval(tabChange, 5000);
}, 15000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With