Show/hide containers by only adding CSS classes without writing javascript code (YUI-based)

This post will show you how to add the collapse/expand functionality in your HTML pages, perfect for FAQs by only adding two class names to your existing page and including the scripts below. Of course it’s all YUI-based and also a demo of the fantastic YUI selector utility.

What does the script do ?

OK, suppose you have a FAQ page where you have traditional anchor methods, i.e you click on the question and then you go to the bottom of the page to get the answer or you get redirected to another page. But now your users are complaining your site’s not trendy enough and want to have the answer displayed immediately after clicking the question.

The solution.

After downloading the javascript file, include it at the bottom of your page with the following HTML code:

<script type="text/javascript" src=""></script> 
<script type="text/javascript" src="js/toggler.js"></script>

We need to include the selector utility which will be used to retrieve a collection of elements that match a given CSS selector. For e.g if we want to retrieve all div nodes in HTML page having the class “foo”, we can write :

var myNodes = YAHOO.util.Selector.query('');

The selector is used in the toggler.js file.

After adding the scripts, now you have to add CSS classes to your containers. For example for the FAQ, for questions (or main, call it whatever you want), you add the class “htmlblog-main” and for the answers (or sub), add the “htmlblog-sub” class.

Before :

<div>1. Question</div>
<div>2. Question 2</div>
<div>Answer 2</div>

After :

<div class="htmlblog-main">1. Question</div>
<div class="htmlblog-sub">Answer1</div>
<div class="htmlblog-main">2. Question 2</div>
<div class="htmlblog-sub">Answer 2</div>

If you already had a class for that container, no problem you can add the htmlblog-main or htmlblog-sub class :

<div class="myclass htmlblog-main">1. Question</div>

What next ?

That’s all ! All your answer containers will be hidden and questions will have a [+] besides them. Pretty easy

Am I obliged to use the htmlblog-main and html-sub classes ? And I don’t want to use div tags, I want li tags.

Don’t worry, if you don’t like the class names you can put whatever you want but you’ll have to edit the toggler.js file at the following lines :

YAHOO.util.Event.addListener(window, 'load', function(){
	YAHOO.htmlblog.init('div', 'htmlblog-main', 'htmlblog-sub');

For e.g, if you’re using li tags instead of divs with the “myMainClass” as main and “mySubClass” as sub, the code goes :

YAHOO.util.Event.addListener(window, 'load', function(){
	YAHOO.htmlblog.init('li', 'myMainClass', 'mySubClass');

I’am getting an alert saying “Number of main and subs incorrect”.

That means the number of main/subs are not the same. You need to have the number of the main class equals the number of the sub class.

Be Sociable, Share!