Full JavaScript FAQ Source Code

// FAQ object that handles our actions for our page.
var FAQ = function (id)
{

	var self = this;

	// Initialize the object and load up the data
	self.init = function (id)
	{

		self.holder = document.getElementById(id);
		self.load();
	};

	// Load in all the FAQs fron the markup
	self.load = function ()
	{
		self.questions = [];

		
		var eles = self.holder.getElementsByTagName('div');
		for (var i = 0; i < eles.length; i++)
		{

			if (eles[i].className == 'faq-entry')
			{
				var q = eles[i].getElementsByTagName('a');

				var a = eles[i].getElementsByTagName('div');

				if (q.length == 1 && a.length == 1)
				{

					// Hide the answer and set up the click listener
					a[0].style.display = 'none';
					self.setupListener(q[0], a[0]);

				
					self.questions.push({
						question : q[0],
						answer   : a[0]
					});
				}

			}
		}
	};

	// Creates a listener on the click event of the <question> to show the <answer>

	self.setupListener = function (question, answer)
	{
		question.onclick = function (e)
		{
			// Hide all

			for (var i = 0; i < self.questions.length; i++)
			{

				self.questions[i].answer.style.display = 'none';
			}

			answer.style.display = 'block';

			// Return false to keep from following our href
			return false;
		};
	};

	self.init(id);
};

// We want to fire our FAQ when the page is done loading
window.onload = function ()

{
	var faq = new FAQ('faq-list');
};