Logo Logo
Back to list
WEB

How to Create an Interactive Hamburger Icon

14. 03. 2026
How to Create an Interactive Hamburger Icon

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">
&lt;!-- Bootstrap Icons Link --&gt;
&lt;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)"&gt;

&lt;style&gt;
    .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 */ } } &lt;/style&gt; </head> <body> &lt;!-- Toggle Button --&gt; &lt;button class="menu-toggle" id="hamburger-btn" type="button" aria-label="Menu"&gt; &lt;i class="bi bi-list" id="nav-icon"&gt;&lt;/i&gt; &lt;/button&gt; &lt;script&gt; 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'); } }); &lt;/script&gt; </body> </html>

Hvala za obisk! Dodajam politiko zasebnosti.

© 2024 Vse pravice pridržane.

Vam je koda pomagala? Če želite podpreti moj trud pri pripravi vodičev in vzdrževanju strani, mi lahko namenite donacijo za kavo.