Niall McMahon

The ramblings and occasional intellect from a web developer, music lover and genealogist.

MENU

Code snippet: Link directly to jQuery tabs

I've used Klaus Hartl's jquery.tabs.js plugin for a while now and it works well and is easy to implement. I faced a problem at work recently when a newsletter was being sent out that needed to link directly to a tab on a page on our company's website. Linking to the page shows the first tab only. Below is a solution for this problem.

The basic HTML for a set of tabs using the jquery.tabs.js plugin is as follows:

		<ul id="tabs">
			<li><a href="#first-tab">First Tab</a></li>
			<li><a href="#second-tab">Second Tab</a></li>
			<li><a href="#third-tab">Third Tab</a></li>
		</ul>
		<div id="tab-container">
			<div class="tab-content" id="first-tab">
				...
			</div>
			<div class="tab-content" id="second-tab">
				...
			</div>
			<div class="tab-content" id="third-tab">
				...
			</div>
		</div>

And the jQuery to make them work:

		$(".tab-content").hide(); // Hide all content
		$("#tabs li:first").addClass("active").show(); // Activate first tab
		$(".tab-content:first").show(); // Show first tab content
	
		// Clicking on each tab
		$('#tabs li').click(function() {
			
			$("#tabs li").removeClass("active"); // Remove any "active" class
			$(this).addClass("active"); // Add "active" class to selected tab
			$(".tab-content").hide(); // Hide all tab content
	
			var activeTab = $(this).find("a").attr("href"); // Find the href attribute value to identify the active tab + content
			$(activeTab).fadeIn(); // Fade in the active ID content
			return false;
			
		});

Adding the following code after the click() event for the list items, will allow you to directly link to a tab:

		if(window.location.hash) { 
			var hash = window.location.hash;
			$('#tabs li').each(function() {
				if($(this).find('a').attr('href') == hash) { 
					
					$("#tabs li").removeClass("active");
					$(this).addClass("active");
					$(".tab-content").hide();
					
					var activeTab =  $(this).find('a[href=' + hash + ']').attr('href');
					$(activeTab).fadeIn();
					return false;
					
				}
			});
		}

You can now link to a tab like this:

<a href="/path/to/your/page.php#second-tab">Link to second tab</a>
Bookmark and Share
blog comments powered by Disqus