jQuery UI Tabs with Next/Previous

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

Tabbed areas are lovely, but when you start getting to more than 3 or 4 different tabs, they start to get a little crowded and it makes sense to provide alternative navigation of them. I think it makes sense to supply universally located Next/Previous buttons, so without even moving your cursor you can click through each of them.

View Demo   Download Files

jQuery UI makes creating tabbed areas very easy, so the framework is based on that. But we are on our own as far as Next/Previous buttons. Fortunately, jQuery UI tabs do have a function-thing that can be called to switch tabs. We can bind it to text links to accomplish switching tabs:

$('#my-text-link').click(function() { // bind click event to link
    $tabs.tabs('select', 2); // switch to third tab
    return false;
});

But we want to do this (hopefully) as smart-ly as we can. So we want to:

  • Add the links dynamically to each panel. If a panel is added or removed, the Next/Previous buttons automatically adjust to the new flow. Plus, links won’t be there awkwardly with JavaScript disabled
  • Make sure there is no “Previous” button on the first panel
  • Make sure there is no “Next” button on the last panel

This is how I did it:

$(function() {

	var $tabs = $('#tabs').tabs();
	
	$(".ui-tabs-panel").each(function(i){
	
	  var totalSize = $(".ui-tabs-panel").size() - 1;
	
	  if (i != totalSize) {
	      next = i + 2;
   		  $(this).append("<a href='#' class='next-tab mover' rel='" + next + "'>Next Page &#187;</a>");
	  }
	  
	  if (i != 0) {
	      prev = i;
   		  $(this).append("<a href='#' class='prev-tab mover' rel='" + prev + "'>&#171; Prev Page</a>");
	  }
   		
	});
	
	$('.next-tab, .prev-tab').click(function() { 
           $tabs.tabs('select', $(this).attr("rel"));
           return false;
       });
       

});