javascripthtmlmenuonclickshow-hide

Hide/show menu onclick javascript


I want to do a hide/show menu that shows when you click the p-tag with id menu and hides when you click the same p-tag — but apparently I'm useless on JavaScript. I don't want to use jQuery, I really want to learn this! Someone out there?

Here is my HTML:

<nav>
    <p id="menu"> Menu</p>
        <ul id="menu-box">
            <li><a href="index.html">Start</a></li>
            <li><a href="animal.html">Animal</a></li>
            <li><a href="pictures.html">Pictures</a></li>
        </ul>
    </nav>  

Here is my JavaScript (so far):

function setUp() {
    document.getElementById("menu").onclick = setMenu;
}

function setMenu() {
    var menuBox = document.getElementById("menu-box");
    menuBox.className = "menuBox";   
}

setUp();

Solution

  • function toggleMenu() {
      var menuBox = document.getElementById('menu-box');    
      if(menuBox.style.display == "block") { // if is menuBox displayed, hide it
        menuBox.style.display = "none";
      }
      else { // if is menuBox hidden, display it
        menuBox.style.display = "block";
      }
    }
    <p id="menu" onclick="toggleMenu()"> Menu</p>
    <ul id="menu-box" style="display: block">
      <li><a href="index.html">Start</a></li>
      <li><a href="animal.html">Animal</a></li>
      <li><a href="pictures.html">Pictures</a></li>
    </ul>