Button only

Recipe 7.7 Add sub menus

Sample:

Code:

<style>
  [aria-expanded="false"] + .nav-sublist {
    display: none;
  }
</style>

<nav aria-label="Main">
  <ul class="nav-list">
    <li>
      <a href="/home">Home</a>
    </li>

    <li>
      <button aria-expanded="false" aria-controls="mainnav-2-sub" class="mainnav-toggle-sub">
        Products
      </button>

      <ul class="nav-sublist" id="mainnav-2-sub">
        <li>
          <a href="/products">All Products</a>
        </li>
        <li>
          <a href="/products/electronics">Electronics</a>
        </li>
        <li>
          <a href="/products/sports">Sports and Outdoors</a>
        </li>
        <li>
          <a href="/products/toys">Toys</a>
        </li>
      </ul>
    </li>
  </ul>
</nav>

<script>
const nav = document.querySelector(' nav')

nav.addEventListener('click', e => {
  if (e.target.classList.contains('mainnav-toggle-sub')) {
    e.preventDefault()
    const isOpen = e.target.getAttribute('aria-expanded') === "true"
    e.target.setAttribute('aria-expanded', !isOpen);
  }
})
</script>