Simple Tab View with YUI 3

Tab Views (i.e. tabbed-content) are ubiquitous on the web.

Examples of tabbed content areas from popular websites

Tabbed content is everywhere on the web

These interface elements are super simple to implement these days, so it seemed useful to show how a simple Tab View could be created using YUI 3.

The HTML Markup

The markup is a navigation list linking to content sections in the content area; simple and semantic. Some CSS classes are added to help with the layout, styling and JavaScript hooks.

<div class="tabview">

	<ul class="tabview-tabs">
		<li class="tabview-active"><a href="#content1">Tab 1</a></li>
		<li><a href="#content2">Tab 2</a></li>
		<li><a href="#content3">Tab 3</a></li>
	</ul>

	<div class="tabview-content">
		<div id="content1"><p>Content for Tab 1</p></div>
		<div id="content2" class="tabview-hidden"><p>Content for Tab 2</p></div>
		<div id="content3" class="tabview-hidden"><p>Content for Tab 3. bla bla bla…</p></div>
	</div>

</div>

The JavaScript Using YUI 3

Using the Y.Node Class made adding the behavior a breeze.

When a tab is clicked:

  1. I add the tabview-active CSS class to it and remove the class for all other tabs.
  2. I then find the corresponding content section and remove the tabview-hidden CSS class from it and make sure all the other content sections are hidden.
YUI().use('node', function(Y){

	Y.all('.tabview').each(function(){
		this.delegate('click', toggleTabs, '.tabview-tabs a');
	});

	function toggleTabs (e) {

		var tabview = e.container,
			tabs = tabview.all('.tabview-tabs li'),
			contents = tabview.all('.tabview-content > *'),
			tab = e.currentTarget.get('parentNode');

		contents.addClass('tabview-hidden')
			.item(tabs.removeClass('tabview-active').indexOf(tab.addClass('tabview-active')))
				.removeClass('tabview-hidden');

		e.preventDefault();
	}

});

Working Example

Screenshot of the Simple Tabs Example

The example using this code

View working example

7 Tweets 2 Comments 1 Other Comment

2 Responses to “Simple Tab View with YUI 3”


Leave a Reply

Additional comments powered by BackType