jQuery & AJAX’s Sweet Tab

Share this article

Introduction

With the world turning into a new age of web designing, it’s important to organize the content of a page in an intuitive and eye-catchy manner. Developer’s one principle in dividing texts is to use a tab. Tab allows you to use more content in a limited space and provide way of accessing it. Today, we’re going to discuss on how to make an AJAX powered tab with the assistance of CSS3 and jQuery.
Sweettabs.jpg

XHTML

Start with the XHTML markup.

<ul class="tabContainer">
	<!-- The jQuery generated tabs go here -->
</ul>

<div class="clear"></div>

<div id="tabContent">
	<div id="contentHolder">
		<!-- The AJAX fetched content goes here -->
	</div>
</div>

As you have noticed, markup looks too simple to be true. This is because we’re missing the code for the tabs, it is inserted dynamically be jQuery on page load. This makes it extremely easy to add new tabs as you need to add it on JavaScript side.

<li>
	<a href="#" class="tab green">Tab two
		<span class="left"></span>
		<span class="right"></span>
	</a>
</li>

This is the code that’s inserted by jQuery for each tab. It consists of a LI element positioned inside the .tabContainer unordered list above.

CSS

Now it’s the time for the CSS styling of the tab page.

.tabContainer{
	/* The UL */
	float:right;
	padding-right:13px;
}

#contentHolder{
	background-color:#EEEEEE;
	border:2px solid #FFFFFF;
	height:300px;
	margin:20px;

	color:#444444;
	padding:15px;
}

#tabContent{
	background-color:#333;
	border:1px solid #444;
	margin-top:-15px;
	width:100%;
}

#tabContent, .tabContainer li a,#contentHolder{
	-webkit-box-shadow:0 0 2px black;
	-moz-box-shadow:0 0 2px black;
	box-shadow:0 0 2px black;
}

.tabContainer li{
	/* This will arrange the LI-s next to each other */
	display:inline;
}

.tabContainer li a,.tabContainer li a:visited{
	/* Styling the hyperlinks of the tabs as colorful buttons */

	float:left;
	font-size:18px;

	/* display:block allows for additinal CSS rules to take effect, such as paddings: */
	display:block;

	padding:7px 16px 1px;
	margin:4px 5px;
	height:29px;

	/* Giving positioning */
	position:relative;

	/* CSS3 text-shadow */
	text-shadow:1px 1px 1px #CCCCCC;
}

The styling above uses the latest CSS3 rules that add up to the overall look and feel of the page. Box-shadow property adds a shadow below the tabs while the #tabContent div and the #contentHolder.

#overLine{
	/* The line above the active button. */
	position:absolute;

	height:1px;
	background-color:white;
	width:90px;

	float:left;
	left:1px;
	top:-5px;
	overflow:hidden;
}

#main{
	margin:0 auto;
	position:relative;
	width:700px;
}

ul .left{
	/* The left span in the hyperlink */

	height:37px;
	left:0;
	position:absolute;
	top:0;
	width:10px;
}

ul .right{
	/* The right span in the hyperlink */

	height:37px;
	right:0;
	position:absolute;
	top:0;
	width:10px;
}

/* Styling the colors individually: */

ul a.green{	background:url(img/green_mid.png) repeat-x top center;	color:#24570f;}
ul a.green span.left{ background:url(img/green_left.png) no-repeat left top;}
ul a.green span.right{ background:url(img/green_right.png) no-repeat right top;}

/* .. Analogical styles for the red, blue and orange color .. */

/* The hover states: */
ul a:hover{	background-position:bottom center; text-decoration:none;}
ul a:hover span.left{ background-position:left bottom;}
ul a:hover span.right{ background-position:right bottom;}

.preloader{
	display:block;
	margin:120px auto;
}

As you can see, there are defined different backgrounds for the hyperlink and the left/right spans that depend on the color class that is assigned. We can successfully change a number of CSS styles and we’ll have a completely different design of the tab.

jQuery

This is where the magic starts.

<link rel="stylesheet" type="text/css" href="styles.css" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>

We’ve used the famous Google CDN and we add our own script.js file, which contains all of our scripts.
Here is the detailed explanation of what exactly jQuery does:
*jQuery library is automatically downloaded from Google’s Content Depository Network.
*$(document).ready() is queued for execution and as well as the function that is provided as a parameter is run when the DOM has finished loading.
*The tabs object is looped with the $.each() method and individual elements are created and appended to the .tabContainer (covered in step one).
*Event listeners for the click event.

$(document).ready(function(){
	/* This code is executed after the DOM has been completely loaded */

	/* Defining an array with the tab text and AJAX pages: */

	var Tabs = {
		'Tab one'	: 'pages/page1.html',
		'Tab two'	: 'pages/page2.html',
		'Tab three'	: 'pages/page3.html',
		'Tab four'	: 'pages/page4.html'
	}

	/* The available colors for the tabs: */
	var colors = ['blue','green','red','orange'];

&nbsp;	/* The colors of the line above the tab when it is active: */
	var topLineColor = {
		blue:'lightblue',
		green:'lightgreen',
		red:'red',
		orange:'orange'
	}

	/* Looping through the Tabs object: */
	var z=0;
	$.each(Tabs,function(i,j){
		/* Sequentially creating the tabs and assigning a color from the array: */

		var tmp = $(''+i+' ');

		/* Setting the page data for each hyperlink: */

		tmp.find('a').data('page',j);

		/* Adding the tab to the UL container: */
		$('ul.tabContainer').append(tmp);
	})

The above source is the script.js first part. You can add your very own tabs on the page by inserting a new property to the Tabs object. The left part holds tab’s name in single quotes, whereas right part contains the AJAX URL which is going to be fetched and displayed in the #content Holder div.

/* Caching the tabs into a variable for better performance: */
	var the_tabs = $('.tab');

	the_tabs.click(function(e){

		/* "this" points to the clicked tab hyperlink: */
		var element = $(this);

&nbsp;		/* If it is currently active, return false and exit: */
		if(element.find('#overLine').length) return false;

&nbsp;		/* Detecting the color of the tab (it was added to the class attribute in the loop above): */

		var bg = element.attr('class').replace('tab ','');

&nbsp;		/* Removing the line: */
		$('#overLine').remove();

&nbsp;		/* Creating a new div element with jQuery 1.4 by passing an additional object parameter: */

		$('<div>',{
			id:'overLine',
			css:{
				display:'none',
				width:element.outerWidth()-2,
				background:topLineColor[bg] || 'white'
			}}).appendTo(element).fadeIn('slow');

&nbsp;		/* Checking whether the AJAX fetched page has been cached: */

		if(!element.data('cache'))
		{
			/* If no cache is present, show the gif preloader and run an AJAX request: */
			$('#contentHolder').html('<img src="img/ajax_preloader.gif" width="64" height="64" class="preloader" />');

&nbsp;			$.get(element.data('page'),function(msg){
				$('#contentHolder').html(msg);

&nbsp;				/* After page was received, add it to the cache for the current hyperlink: */
				element.data('cache',msg);
			});
		}
		else $('#contentHolder').html(element.data('cache'));

&nbsp;		e.preventDefault();
	})

	/* Emulating a click on the first tab, so that the content area is not empty: */
	the_tabs.eq(0).click();

});

The jQuery data() method has been used many times throughout the code. It sends data to an element by calling the method with two parameters $(‘#selector’).data(‘label’,”String Data”) This assigns the “String Data” which is a string to the element and granting access later to it by calling the data method without the other parameter.
By using these, we have our very own simple caching system for the AJAX requests.

Conclusion

By following the steps above, you should have your pretty AJAX-enabled colorful tabs with jQuery and CSS3. It’s not that hard right?
If you liked this tutorial, be sure to visit jQuery4u.com frequently for more great tutorials and tricks!

See live Demo
Download

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week