Advertisement
  1. Code
  2. JavaScript

Sexy Animated Tabs Using MooTools

Scroll to top
Read Time: 14 min

One modern, attractive way of placing a lot of content into a little space is by using a tab system. This tutorial will show you how to create a sexy, animated tab system complete with CSS sprites, cookies, and animated tab swapping.


MooTools Tabs

Assumptions

There are a few assumptions and notes that we're going into this system with:

  • We'll be using the most recent version of MooTools: 1.2.4.
  • The client must support JavaScript.
  • We'll be using PHP for any server-side scripting. Any server-side language of your choosing will also work its corresponding syntax/methods

The tutorial also assumes a basic knowledge of javascript. A tiny bit of MooTools or JavaScript framework experience will help.

The Plot

So how is this awesome system going to work? Here's the basic outline:

  • When the page loads, we output two UL lists with list items: the first list contains the tabs, the second list contains the tab content items.
  • For each tab set we output, we check for a given cookie that could tell us which tab should be displayed based on the previous visit. If no cookie is present, we assume the first tab.
  • When the user clicks a tab, the current content item for that tab slides out of view and the new tab content slides in.
  • We save the index of the tab in a cookie for future loading purposes (i.e. we want to make the last-clicked-tab the first to display on the next page/visit.)

The system itself is pretty bulletproof. If the user doesn't allow cookies, the starting tab for each list will always be 0.
If JavaScript support isn't present, the tabs wont be seen on screen as we'll display:none; them initially.

Step One: The HTML

The HTML to accomplish the tab system and corresponding content items is incredibly simple in structure.

1
2
<div class="tab-container">
3
	<ul id="tabs1" class="tabs">
4
		<li>Tab 1</li>
5
		<li>Tab 2</li>
6
		<li>Tab 3</li>
7
		<li>Tab 4</li>
8
	</ul>
9
	<div class="clear"></div>
10
	<ul id="contents1" class="tabs-content">
11
		<li>This is the content for tab 1.</li>
12
		<li>This is the content for tab 2.</li>
13
		<li>This is the content for tab 3.</li>
14
		<li>This is the content for tab 4.</li>
15
	</ul>
16
</div>

We will be modifying the above HTML with PHP later in this tutorial to create a more robust system.

MooTools Tabs

Step Two: CSS

As with any CSS and HTML combo, you may style the tabs and their content items however you'd like.
I've chosen to use Facebook-style CSS sprites for my example tabs.
Realize that you'll want to style the following items in a specific fashion so that the system works:

  • The tab content items must have a height of 0 and their overflow's hidden. That allows for all of the content items to be "hidden", so to speak, when the page loads.
  • Between the "ul.tabs li a" and "ul.tabs li a.active" CSS selectors, you'll want to assign the "active" selector a different look so that the user knows its' the currently selected tab.
1
2
/* tabs structure */
3
.tab-container	{ width:320px; background:#eee; padding:5px 10px; }
4
ul.tabs			{ list-style-type:none; margin:0; padding:0; }
5
	ul.tabs li		{ float:left; margin:10px 5px 0 0; }
6
	ul.tabs li a	{ padding:5px 10px; border:1px solid #ddd; font-weight:bold; background:url(tab-sprite.jpg) 0 0 repeat-x; color:#000; text-decoration:none; }
7
	ul.tabs li a.active	{ border-color:#028433; background-position:0 -96px; color:#fff; } /* sprite! background position swap */
8
		ul.tabs li a.active:hover	{ text-decoration:none; cursor:default; }
9
	ul.tabs li:hover	{ text-decoration:underline; }
10
ul.tabs-content	{ margin:10px 0 0 0; padding:0; }
11
	ul.tabs-content li	{ height:0; overflow:hidden; margin:0; padding:0; }
12
13
/* clears floats */
14
div.clear		{ clear:both; }
15
		
16
/* ie fixes */
17
* html ul.tabs-content li { float:left; } /* ie6 */
18
*+ html ul.tabs-content li { width:99%; float:left; } /* ie7 */

Note that we need to implement a few Internet Explorer-specific fixes; ugly, but necessary.

MooTools Javascript Framework

Step Three: The MooTools Javascript

One of the great advantages of MooTools is the powerful Class system.
MooTools classes allow for flexible, organized, and extendable functionalities.
Our MooTools class will be called "TabSet." Since the TabSet class performs many actions,
lets break down each part of the class.

The first line is always giving the class a name:

1
2
/* give the class a name */
3
var TabSet = new Class({

Next we need to create an object that will hold our class' options:

1
2
	options: { //default tab options

3
		activeClass: 'active', //css class

4
		cookieName: '', //no name means no cookie

5
		cookieOptions: { //options for the cookie, if cookie's wanted

6
			duration: 30, //30 days

7
			path: '/'
8
		},
9
		startIndex: 0 //start with this item if no cookie or active

10
	},

Our options allow us to define:

  • activeClass: The CSS class that should be assigned to the currently-selected (or "active") tab.
  • cookieName: The name of the cookie that will represent this tab set. If you don't define a cookie name, cookies wont be used.
  • cookieOptions: An object that holds the options for the cookie.
  • startIndex: The tab to make active initially. Starts with 0. Overridden by the activeClass variable if a cookie is found.

With only three options in the class, TabSet would be considered a relatively simple class.

Next we implement two Options and Events:

1
2
Implements: [Options,Events],

Implementing Options and Events will allow us to correctly handle given options and
fire custom Load and Change events on our lists anywhere within the class.

Next we define the "initialize" method which runs upon creation of every instance of the class:

1
2
	initialize: function(tabs,contents,options) {
3
		//handle arguments

4
		this.setOptions(options); //mix the given options with the default options

5
		this.tabs = $$(tabs); //save the given tabs within the class

6
		this.contents = $$(contents); //save the given "contents" within the class

7
		//determine the "active" tab

8
		var active = (Cookie.read(this.options.cookieName) || this.options.startIndex);  //decide the index that should be active initially

9
		this.activeTab = this.tabs[active].addClass(this.options.activeClass); //now identify the "active" tab

10
		this.activeContent = this.contents[active].setStyle('height','auto'); //identify the "active" content

11
		//run each tab/content combo through the "processItem" method which we'll see below

12
		this.tabs.each(function(tab,i) { this.processItem(tab,this.contents[i],i); },this);
13
		//tabs are ready -- fire the load event!

14
		this.fireEvent('load');
15
	},

Next comes the workhorse method of our TabSet class: processItem:

1
2
	processItem:function(tab,content,i) {
3
		var contentHeight = content.getScrollSize().y;
4
		//add a click event to the tab

5
		tab.addEvent('click',function() {
6
			//if it's not the active tab

7
			if(tab != this.activeTab) {
8
				//stopper

9
				if(e) e.stop();
10
				//remove the active class from the active tab

11
				this.activeTab.removeClass(this.options.activeClass);
12
				//make the clicked tab the active tab

13
				(this.activeTab = tab).addClass(this.options.activeClass);
14
				//tween the old tab content up

15
				//tween the new content down

16
				this.activeContent.set('tween',{
17
					onComplete:function() {
18
						this.activeContent = content.fade('in').set('tween',{ onComplete: $empty }).tween('height',contentHeight);
19
						//fire the tab change event

20
						this.fireEvent('change',[tab,content]);
21
					}.bind(this)
22
				}).setStyles({
23
					height: contentHeight,
24
					overflow: 'hidden'
25
				}).fade('out').tween('height',0);
26
				//save the index to cookie

27
				if(this.options.cookieName) Cookie.write(this.options.cookieName,i);
28
			}
29
		}.bind(this));
30
	}
31
});

Here's the basic outline of what the processItem method does:

  1. Accepts a matching tab, content item, and its index...
  2. Calculates the height of the content element.
  3. Adds a click event to the tab that:
    1. Validates that this tab isn't already active (we don't want to animate or change anything if they click the already-active tab)
    2. Removes the "active" CSS class from the current tab and adds it to the tab that was just clicked.
    3. Slides the current tab's content out of view, then slides the new content into view. The "change" event is fired when the animation is complete.
    4. Saves the new tab's index to the cookie so that when the user reloads the page or goes to another page, the new tab will be selected initially.

And now a sample usage of our class:

1
2
window.addEvent('domready',function() {
3
	var tabset = new TabSet($$('#tabs1 li a'),$$('#contents1 li'),{
4
		cookieName: 'demo-list'
5
	});
6
});

We provide our instance the tab LI A's and the content LI's. We also provide the optional options argument. That's how easy it is to use this class! Here's the complete class with usage:

1
2
/* class */
3
var TabSet = new Class({
4
	options: {
5
		activeClass: 'active', //css class

6
		cookieName: '',
7
		cookieOptions: {
8
			duration: 30, //30 days

9
			path: '/'
10
		},
11
		startIndex: 0 //start with this item if no cookie or active

12
	},
13
	Implements: [Options,Events],
14
	initialize: function(tabs,contents,options) {
15
		//handle arguments

16
		this.setOptions(options);
17
		this.tabs = $$(tabs);
18
		this.contents = $$(contents);
19
		//determine the "active" tab

20
		var active = (Cookie.read(this.options.cookieName) || this.options.startIndex);
21
		this.activeTab = this.tabs[active].addClass(this.options.activeClass);
22
		this.activeContent = this.contents[active].setStyle('height','auto');
23
		//process each tab and content

24
		this.tabs.each(function(tab,i) {
25
			this.processItem(tab,this.contents[i],i);
26
		},this);
27
		//tabs are ready -- load it!

28
		this.fireEvent('load');
29
	},
30
	processItem:function(tab,content,i) {
31
		var contentHeight = content.getScrollSize().y;
32
		//add a click event to the tab

33
		tab.addEvent('click',function(e) {
34
			//stop!

35
			if(e) e.stop();
36
			//if it's not the active tab

37
			if(tab != this.activeTab) {
38
				//remove the active class from the active tab

39
				this.activeTab.removeClass(this.options.activeClass);
40
				//make the clicked tab the active tab

41
				(this.activeTab = tab).addClass(this.options.activeClass);
42
				//tween the old tab content up

43
				//tween the new content down

44
				this.activeContent.set('tween',{
45
					onComplete:function() {
46
						this.activeContent = content.fade('in').set('tween',{ onComplete: $empty }).tween('height',contentHeight);
47
						//fire the tab change event

48
						this.fireEvent('change',[tab,content]);
49
					}.bind(this)
50
				}).setStyles({
51
					height: contentHeight,
52
					overflow: 'hidden'
53
				}).fade('out').tween('height',0);
54
				//save the index to cookie

55
				if(this.options.cookieName) Cookie.write(this.options.cookieName,i,this.options.cookieOptions);
56
			}
57
		}.bind(this));
58
	}
59
});
60
61
62
/* usage */
63
window.addEvent('load',function() {
64
	var tabset = new TabSet($$('#tabs1 li a'),$$('#contents1 li'),{
65
		cookieName: 'demo-list'
66
	});
67
});
MooTools CookiesMooTools CookiesMooTools Cookies

Step Four: PHP / HTML

Remember how I said we'd be modifying our original HTML with PHP? Now's the time. Since we may
have a cookie set for our TabSet, we should attempt to detect that when we output the tab HTML.
Why? Because we want the tabs to load in smoothly. We also want to accommodate for users that don't have JavaScript or cookies enabled.
Without this PHP, you may notice a slight "jump" in the active content area.

1
2
<?php
3
	/*

4
		Removes a desired variable from the querystring

5
		Credit:  http://www.addedbytes.com/code/querystring-functions/

6
	*/
7
	function remove_querystring_var($url, $key) { 
8
		$url = preg_replace('/(.*)(\?|&)' . $key . '=[^&]+?(&)(.*)/i', '$1$2$4', $url . '&');
9
		$url = substr($url, 0, -1);
10
		return ($url); 
11
	}
12
	
13
	/* generate the urls */
14
	$demo_tabs_url = remove_querystring_var($_SERVER['REQUEST_URI'],'demo-list');
15
	$demo_tabs_url.= (is_numeric(strpos($demo_tabs_url,'demo-list')) ? '&' : '?').'demo-list=';
16
	
17
	/* current tab */
18
	$current_tab = isset($_COOKIE['demo-list']) ? (int) $_COOKIE['demo-list'] : (isset($_GET['demo-list']) ? (int) $_GET['demo-list'] : 0);
19
	
20
?>
21
22
<div class="tab-container">
23
	<ul id="tabs1" class="tabs">
24
		<li><a href="<?php echo $demo_tabs_url.'0'; ?>" <?php echo $current_tab == '0' ? ' class="active"' : ''; ?>>Tab 1</a></li>
25
		<li><a href="<?php echo $demo_tabs_url.'1'; ?>"  <?php echo $current_tab == '1' ? 'class="active"' : ''; ?>>Tab 2</a></li>
26
		<li><a href="<?php echo $demo_tabs_url.'2'; ?>"  <?php echo $current_tab == '2' ? 'class="active"' : ''; ?>>Tab 3</a></li>
27
		<li><a href="<?php echo $demo_tabs_url.'3'; ?>"  <?php echo $current_tab == '3' ? 'class="active"' : ''; ?>>Tab 4</a></li>
28
	</ul>
29
	<div class="clear"></div>
30
	<ul id="contents1" class="tabs-content">
31
		<li <?php echo $current_tab == '0' ? ' style="height:auto;"' : ''; ?>>This is the content for tab 1. This is the content for tab 1. This is the content for tab 1. This is the content for tab 1. This is the content for tab 1. This is the content for tab 1. This is the content for tab 1. This is the content for tab 1.</li>
32
		<li <?php echo $current_tab == '1' ? ' style="height:auto;"' : ''; ?>>This is the content for tab 2. This is the content for tab 2. This is the content for tab 2. This is the content for tab 2. This is the content for tab 2. This is the content for tab 2. This is the content for tab 2. This is the content for tab 2.</li>
33
		<li <?php echo $current_tab == '2' ? ' style="height:auto;"' : ''; ?>>This is the content for tab 3. This is the content for tab 3. This is the content for tab 3. This is the content for tab 3. This is the content for tab 3. This is the content for tab 3. This is the content for tab 3. This is the content for tab 3.</li>
34
		<li <?php echo $current_tab == '3' ? ' style="height:auto;"' : ''; ?>>This is the content for tab 4. This is the content for tab 4. This is the content for tab 4. This is the content for tab 4. This is the content for tab 4. This is the content for tab 4. This is the content for tab 4. This is the content for tab 4.</li>
35
	</ul>
36
</div>

Step Five: PHP: Accommodating For Users Without Javascript or Cookies

Some users don't enable JavaScript or cookies for security purposes. We still want our system to work for them though. If you recall from the previous block of code,
we're using links with a querystring key of "demo-list" to denote a change in tab. The following block of PHP at the top of the page (before ANY output) will
help us change the cookie value to the requested tab.

1
2
<?php
3
	/* handle the cookies */
4
	if($_GET['demo-list']) {
5
		/* set the new cookie */
6
		setcookie('demo-list',(int) $_GET['demo-list'],time()+60*60*24*30,'/'); //30 days

7
		if($_COOKIE['demo-list']) {
8
			header('Location: '.remove_querystring_var($_SERVER['REQUEST_URI'],'demo-list'));
9
			exit();
10
		}
11
	}
12
?>

Note that we only refresh the page if we can verify that the cookie has been set. If the cookie hasn't been set, the user has their cookies disabled.

MooTools CookiesMooTools CookiesMooTools Cookies

Mission Accomplished!

Here's a quick summary of the benefits of the MooTools TabSet class:

  • Our class implements Events so that we may create custom events and event handlers.
  • The layout of the entire system is controlled completely by simple HTML and CSS.
  • The use of cookies to remember the previous tab is great usability improvement.
  • The very class that it's a MooTools class allows for it to be easily implemented from project to project.

The Inline MooTools Javascript

I've always advocated coding a desired MooTools functionality "inline" before turning it into a class. Here's the inline MooTools JavaScript code:

1
2
$$('ul.tabs').each(function(tabList) {
3
	//get the content list

4
	var tabContentList = tabList.getNext('ul.tabs-content'), 
5
		//get the name of the cookie, which is the "title" attribute of the tab list

6
		cookie = 'demo-list',
7
		//the start tab index

8
		startIndex = Cookie.read(cookie) || 0,
9
		//get the actual tab LI items

10
		tabs = tabList.set('title','').getElements('li'), 	
11
		//get the content LI items

12
		lis = tabContentList.getElements('li'),
13
		//the tab (LI) that is currently active

14
		activeTab = tabs[startIndex].addClass('active'),
15
		//the content LI that is currently active

16
		activeContent = lis[startIndex].setStyle('height','auto');
17
	//for every tab within this tab/content relationship...

18
	tabs.each(function(tab,i) {
19
		//stopper

20
		if(e) e.stop();
21
		//calculate the respective content item's height

22
		var content = lis[i], contentHeight = content.getScrollSize().y;
23
		//add the click event to the tab which...

24
		tab.addEvent('click',function() {
25
			//if it's not the currently activated tab...

26
			if(tab != activeTab) {
27
				//add and remove the active class from old vs. new tab

28
				activeTab.removeClass('active');
29
				(activeTab = tab).addClass('active');
30
				//start the wipe up, wipe down effect

31
				activeContent.set('tween',{
32
					onComplete:function() {
33
						activeContent = content.fade('in').set('tween',{ onComplete: $empty }).tween('height',contentHeight);
34
					}
35
				}).setStyles({
36
					height: contentHeight,
37
					overflow: 'hidden'
38
				}).fade('out').tween('height','0');
39
				//write to cookie

40
				Cookie.write(cookie,i);
41
				//fin!

42
			}
43
		});
44
	});
45
	//fire click event 	

46
	activeTab.fireEvent('click');
47
});

Notice that all of the "var" statements at the top either become arguments or options for the class. The transition from inline MooTools JavaScript to a class is extremely simple!

MooTools Tabs

Have Improvement Ideas?

Have more ideas for this class? Be sure to share them in the comments below!

Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at nettuts@tutsplus.com.

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial
Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.