An interactive hamburger icon is a key element of mobile websites. It allows us to hide the navigation menu and display it only when the user needs it. For it to work, we need three components: HTML for structure, CSS for styling, and JavaScript to toggle the icon (from three lines to an X) upon clicking.
Full Code Example
Below is the complete HTML document code. It includes the link to the Bootstrap Icons library, necessary styles, and the JavaScript logic for toggling icons.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Hamburger Menu Icon</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap Icons Link --> <link rel="stylesheet" href="[https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css](https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css)"> <style> .menu-toggle { width: 45px; height: 45px; border: none; background: #1e1e1e; color: #87d5fe; cursor: pointer; border-radius: 8px; display: flex; align-items: center; justify-content: center; transition: all 0.2s ease; } .menu-toggle i { font-size: 28px; } .menu-toggle:hover { background-color: #333; }/* The icon appears at a resolution of 1280px or as set otherwise */ @media screen and (max-width: 1280px) { .menu-toggle { display: flex; /* Displays the button on mobile devices and tablets */ } }
</style> </head> <body> <!-- Toggle Button --> <button class="menu-toggle" id="hamburger-btn" type="button" aria-label="Menu"> <i class="bi bi-list" id="nav-icon"></i> </button> <script> const btn = document.getElementById('hamburger-btn'); const icon = document.getElementById('nav-icon'); btn.addEventListener('click', () => { if (icon.classList.contains('bi-list')) { icon.classList.replace('bi-list', 'bi-x-lg'); } else { icon.classList.replace('bi-x-lg', 'bi-list'); } }); </script> </body> </html>