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 the structure, CSS for the appearance, and JavaScript, which changes the icon (from three lines to an X) upon clicking.
Complete Code Example
Below is the complete code for the HTML document. It includes a link to the Bootstrap Icons library, the necessary styles, and the JavaScript logic for toggling the 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">
<!-- Link to Bootstrap icons -->
<link rel="stylesheet" href="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;
}<br><br> /* The icon appears at 1280px resolution 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>
<!-- Button with icon -->
<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>