jQueryを使って超シンプルなアコーディオンを作る

jQueryを使った超シンプルなアコーディオンを作ってみました。#simpleAccordionを与えたdivの子要素であるh2をクリックするとその直後のdiv要素が開くと言うものです。

まずはデモをご覧下さい。

View Demo

マークアップは次のようにします。

HTML Code

<div id="simpleAccordion">
<h1>jQuery Simple Accordion</h1>
<h2>Click This</h2>
<div>
<p>example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text </p>
</div>
<h2>Click This</h2>
<div>
<p>example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text </p>
</div>
<h2>Click This</h2>
<div>
<p>example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text example text </p>
</div>
<!-- // end #myAco --></div>

head要素に次のスクリプトを書きます。もちろんjQueryが必要です。

jQuery Code

<script type="text/javascript" src="../js/jquery-1.2.3.pack.js"></script>
<script type="text/javascript">
$(function()
{
	$("div#simpleAccordion div").hide();
	$("div#simpleAccordion h2").each(function(i)
	{
		var elementVal = $(this).next("div");
		$(this).click(function()
		{
			elementVal.toggle("normal");
		});
	});
});
</script>

スクリプトの解説ですが、$("div#simpleAccordion div")で#simpleAccordionの子要素のdivをhideイベントで非表示にしておきます。

次にeachメソッドでelementVal配列に自身(h2)の直後に出てくるdiv要素を格納します。対応するh2がクリックされた時にh2直後のdivをtoggleイベントで表示・非表示を切り替えます。

今更ですが、jQueryはtoggleで表示・非表示を切り替えてくれるので凄く便利ですね。toggleイベントの引数をslow、fastにするとアニメーションのスピードが変わります。数値でも指定出来ます。

ちなみにh2をクリックさせるのでh2のCSSにcursor: pointerを指定するのを忘れないでください。

よろしければデモをzipでどうぞ

Download