How to Create a droup down menu ?

Dani AI

Generated

asked a simple question and the thread rightly pointed to tutorials: noted HTML/CSS/JS is enough, linked an older Suckerfish approach, and shared free CSS and mega‑menu examples. The practical checklist for a modern dropdown is: semantic markup, visible focus states, keyboard support (Enter/Space/Escape, optional arrow keys), ARIA state for screen readers, and touch-friendly toggles rather than hover-only behavior.

A minimal, robust pattern (markup + CSS + a tiny script to toggle and handle Escape):

HTML

<nav>
  <ul class="menu">
    <li><a href="#">Home</a></li>
    <li class="has-sub">
      <button aria-expanded="false" aria-controls="sub-1">Products</button>
      <ul id="sub-1" class="submenu" hidden>
        <li><a href="#">Product A</a></li>
        <li><a href="#">Product B</a></li>
      </ul>
    </li>
  </ul>
</nav>

CSS

.menu, .submenu { list-style:none; margin:0; padding:0; }
.has-sub { position:relative; }
.submenu { position:absolute; left:0; top:100%; background:#fff; box-shadow:0 2px 6px rgba(0,0,0,.15); }
.submenu[hidden] { display:none; }

JS

document.querySelectorAll('.has-sub > button').forEach(btn => {
  btn.addEventListener('click', () => {
    const expanded = btn.getAttribute('aria-expanded') === 'true';
    btn.setAttribute('aria-expanded', String(!expanded));
    document.getElementById(btn.getAttribute('aria-controls')).hidden = expanded;
  });
  btn.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      btn.setAttribute('aria-expanded','false');
      document.getElementById(btn.getAttribute('aria-controls')).hidden = true;
      btn.focus();
    }
  });
});

Troubleshooting and tips: avoid hover-only solutions (Suckerfish-style) for touch devices; prefer a button toggle with aria-expanded. Watch for parent overflow:hidden clipping submenus and for stacking-context issues (z-index with positioned parents). For complex menus or keyboard arrow navigation, follow the WAI-ARIA patterns (menubutton). For very small, simple toggles the native <details> element can be a quick, accessible alternative (MDN details).

Recommended Answers

All 3 Replies

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.