Pure Javascript Show/Hide Toggle

Category: Computers

This is a pure Javascript solution to toggle (show/hide) a menu.

The below is based on an example by Isabel Castillo, also taking advice from Ben Osborne. It’s been minified using Google’s Closure Compiler, which reduces the script size from 378 bytes to 233 bytes.

This replaces a jQuery solution, which required me to include jquery.min.js (84,320 bytes).

Demonstration

Code

<button id="menu-button">Hide Menu</button>
<nav id="menu">
  <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
  </ul>
</nav>

<script type="text/javascript">var a=document.querySelector("#menu-button"),b=document.querySelector("#menu");a.addEventListener("click",function(){""==b.style.display?(b.style.display="none",a.innerHTML="Show Menu"):(b.style.display="",a.innerHTML="Hide Menu")});</script>

Javascript before minifying

<script type="text/javascript">
// Script to hide/show menu
var button = document.querySelector('#menu-button');
var menu = document.querySelector('#menu');
button.addEventListener('click', function (event) {
      if (menu.style.display == "") {
          menu.style.display = "none";
          button.innerHTML = "Show Menu";
      } else {
          menu.style.display = "";
          button.innerHTML = "Hide Menu";
      }
    }
  );
</script>

Isabel also has a pure Javascript solution for showing/hiding multiple elements.