jQuery Extract Headings for Tab Controls

Hi there. I posted previously about making jQuery tabs, but this week I found myself wanting take that code a bit further. In the old version, the “controls” were written out in a ul above the slides. It got the job done, but wasn’t ideal from a progressive-enhancement point of view (non-JS don’t really have much need for them, so they really shouldn’t be there for those users).

In this version we’re going to include an h3 at the top of each slide and have jQuery pull those out to make the ul controls. The HTML is like so:

<div id="slides">
	<div class="slide">
		<h3>Slide 1</h3>
		<p>This is the content of slide one</p>
	<div class="slide">
		<h3>Slide 2</h3>
		<p>This is the content of slide two</p>

And the jQuery (the new action is in the first fifteen lines):

$(document).ready(function() {
	// Insert the wrapper for the controls
	$('#slides').before('<ul id="slidecontrols"></ul>');
	//For each heading...
	$('#slides div.slide > h3').each(function(){
		// Copy it into the controls
		// and replace the heading markup with list markup, keeping the contained text
		$('#slidecontrols h3').replaceWith('<li><a href="#">' + $(this).text() + '</a></li>');
	// Hide those H3s
	$('.slide > h3').hide();
	//Set the initial state: highlight the first button...
	//and hide all slides except the first one
	$('#slides').find('> div:eq(0)').nextAll().hide();
	//actions that apply on click of any of the buttons
	$('#slidecontrols li').click( function(event) {
		//turn off the link so it doesn't try to jump down the page
		//un-highlight the buttons
		$('#slidecontrols li').removeClass();
		//hide all the slides
		$('#slides > div').hide();
		//highlight the current button
		//get the index of the current button...
		var index = $('#slidecontrols li').index(this);
		//and use that index to show the corresponding slide
		$('#slides > div:eq('+index+')').show();

Happy coding!

Posted June 2010

  • Raj


  • Heffay

    Thanks for this. Perfect solution. An easy show/hide tab menu. I put a lot of stuff in that DIV including image changes on other parts of the page!

  • Hello, it’s possible to have the same thing with a fade transition ?
    Thank’s 😉

This website is hosted by Media Temple. Thanks, guys!