Sunday, September 26, 2010

Creating a vertical navigation bar with collapsible sections

1. Set up the JavaScript. Create a new JavaScript document and attach it to the HTML
file via a script element in the head of the document. (In the example files, this
document has been named vertical-navigation-bar.js.) First, add the
JavaScript lines first shown in the “Enhancing accessibility for collapsible content”
section:
var cssNode = document.createElement('link');
cssNode.setAttribute('rel', 'stylesheet');
cssNode.setAttribute('type', 'text/css');
cssNode.setAttribute('href', 'javascript-overrides.css');
document.getElementsByTagName('head')[0].appendChild(cssNode);
Next, add the toggler script shown in the “Modularizing the collapsible content
script” section, but amend the target element as shown:
function toggle(toggler) {
if(document.getElementById) {
targetElement = toggler.nextSibling;
if(targetElement.className == undefined) {
targetElement = toggler.nextSibling.nextSibling;
}
if (targetElement.style.display == "block")
{
targetElement.style.display = "none";
}
else
{
targetElement.style.display = "block";
}
}
}

2. Amend the list. To each top-level navigation link, add the onclick attribute, as
shown following. And to each second-level list that you initially want to be invisible,
add the class attribute shown. For any list you want to be visible, instead add
style="display: block;".
<li>
<a href="#" onclick="toggle(this); return false;">Section one</a>
<ul class="collapsibleList">
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
<li><a href="#">A link to a page</a></li>
</ul>
</li>

3.
Add a style sheet. Create and save the style sheet document javascriptoverrides.
css, and add the following rule to initially hide any lists with the
collapsibleList class value in JavaScript-enabled browsers.
#navigation ul.collapsibleList {
display: none;
}
The following images show the results (which depict, from left to right, the
default, hover, and active states).

No comments:

Post a Comment