Toggle navigation
☰
HTML
CSS
Scripting
Database
<!DOCTYPE html> <html> <head> <title>JavaScript Hamburger Menu Example</title> <style> body { font-family: sans-serif; margin: 0; } .navbar { background-color: #4a148c; display: flex; justify-content: space-between; align-items: center; padding: 15px 20px; position: relative; } .navbar-brand { color: white; font-size: 1.5em; font-weight: bold; text-decoration: none; } /* The visual hamburger button (hidden on desktop) */ .menu-icon { display: none; color: white; font-size: 28px; cursor: pointer; background: none; border: none; padding: 0; } .nav-links { list-style: none; margin: 0; padding: 0; display: flex; gap: 20px; } .nav-links li a { color: white; text-decoration: none; padding: 10px; display: block; } /* Mobile Layout */ @media (max-width: 600px) { .menu-icon { display: block; /* Show the hamburger */ } .nav-links { display: none; /* Hide the links by default */ flex-direction: column; position: absolute; top: 100%; left: 0; width: 100%; background-color: #380b6b; gap: 0; } .nav-links li a { padding: 15px 20px; border-top: 1px solid #4a148c; } /* JavaScript will add this class to the nav-links ul when clicked */ .nav-links.active { display: flex; } } </style> </head> <body> <nav class="navbar"> <a href="#" class="navbar-brand">Logo</a> <!-- A standard button for accessibility --> <button class="menu-icon" id="menu-btn" aria-label="Toggle Menu">☰</button> <ul class="nav-links" id="nav-menu"> <li><a href="#">Home</a></li> <li><a href="#">Products</a></li> <li><a href="#">Pricing</a></li> <li><a href="#">Contact</a></li> </ul> </nav> <div style="padding: 20px;"> <p>Resize your browser window so it is narrower than 600px. Click the hamburger icon to execute the JavaScript function that toggles the "active" CSS class on the menu.</p> </div> <script> // Select the button and the menu list const menuBtn = document.getElementById('menu-btn'); const navMenu = document.getElementById('nav-menu'); // Add click event listener to the button menuBtn.addEventListener('click', function() { // Toggle the 'active' class on the menu navMenu.classList.toggle('active'); }); </script> </body> </html>