Javascript code snippets07 Jul 2006 03:37 pm
Javascript and DHTML can be used to make collapsible and expandable HTML lists that degrade cleanly (that is, are still usable for visitors who don't have Javascript-enabled web browsers).
Example
This has been tested in Opera, Mozilla (Navigator) and Internet Explorer. Clicking on the arrows expands or collapses sections of the list:
The code
You need to create images called closed.png and open.png to be used for collapsed and expanded lists respectively. When adding more lists, the id values for the img and ul elements must be changed, and the parameters in the call to toggle() in the image's onClick value must be changed to these ids.
CODE:
-
<ul id="collapsibleList">
-
<li>
-
<script type="text/javascript">document.writeln('<img id="iBMImage" src="closed.png" width="15" height="8" alt="Open list" onClick="toggle(\'iBMImage\',\'iBMList\');"/>');
-
</script> IBM </li>
-
</ul><ul id="iBMList">
-
<li>80x86</li>
-
<li>Itanium</li>
-
</ul>
-
<li>
-
<script type="text/javascript">document.writeln('<img id="motorolaImage" src="closed.png" width="15" height="8" alt="Open list" onClick="toggle(\'motorolaImage\',\'motorolaList\');"/>');
-
</script> Motorola </li>
-
<ul id="motorolaList"> <li>680x0</li>
-
<li>PowerPC</li> </ul>
-
-
<script type="text/javascript"> document.getElementById('collapsibleList').style.listStyle="none"; // remove list markers document.getElementById('iBMList').style.display="none"; // collapse list document.getElementById('motorolaList').style.display="none"; // collapse list // this function toggles the status of a list function toggle(image,list){
-
var listElementStyle=document.getElementById(list).style; if (listElementStyle.display=="none"){ listElementStyle.display="block"; document.getElementById(image).src="open.png"; document.getElementById(image).alt="Close list";
-
}
-
else{
-
listElementStyle.display="none"; document.getElementById(image).src="closed.png"; document.getElementById(image).alt="Open list";
-
}
-
}
-
</script>