Collapse/Expand Menu

Summary

An exercise in collapsing and expanding a “menu” when the title is clicked. Made for Flash Experiments portal.

The entire thing is accessible in that if JavaScript is turned off, the menu or list is still displayed. It just might push down everything else if the list is too long.

Example

Date Created

15 Feb 2008.

Help

  1. Just w3schools.com.

Process

Not too complicated.

  1. Make a list.
  2. Title list and style it.
  3. Control visibility from JS.
  4. Make variable for list and other elements.
  5. Use JS to make the list appear when the menu title is clicked.
  6. Make conditional statement so clicking the title can display and hide the list indefinitely.
  7. Make the title look like it's a link when hovered.
  8. Export the script.

The Code

Here’s the code. Please link back here if you’re using it.

Put this JS in the head tag.


function doIt(){

    var menu=document.getElementById("menu"); //makes variable for the list
    menu.style.display="none"; //hide the list
    var listSwitch=false; //false means the list is hidden;
    
    var menuTitle=document.getElementById("menuTitle"); //makes variable for the title
    menuTitle.onmouseover=menuTitle.style.cursor="pointer";
    
    function expandCollapseList(){
        if (listSwitch==false){ //if the switch is "off"
            menu.style.display="block"; //show list
            listSwitch=true; //switch becomes "on"
        }
        else if(listSwitch==true){
            menu.style.display="none"; //hide list
            listSwitch=false; //now the list is hidden, which makes it false;
            }
    }
        
    menuTitle.onclick=expandCollapseList;
}
    
onload=doIt;

Put this HTML in the body tag.


<p id='menuTitle' >Click here to open/close menu</p>
<ul id='menu' >
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
</ul>
            

Return to top