xxxxxxxxxx
Here is one way you can create a hamburger menu using JavaScript:
1.Create the HTML structure for the hamburger menu. This could include a button element with a class of "hamburger" and a navigation element with a class of "nav":
<button class="hamburger">Menu</button>
<nav class="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
2.Use CSS to style the hamburger menu and hide the navigation by default. You can also use CSS to style the hamburger button and define the hamburger menu's toggle states (e.g., open and closed):
.nav {
display: none;
}
.hamburger {
display: block;
cursor: pointer;
}
.hamburger.open .bar1,
.hamburger.open .bar2,
.hamburger.open .bar3 {
width: 22px;
background-color: #333;
}
.hamburger.open .bar1 {
-webkit-transform: rotate(-45deg) translate(-4px, 4px);
transform: rotate(-45deg) translate(-4px, 4px);
}
.hamburger.open .bar2 {
opacity: 0;
}
.hamburger.open .bar3 {
-webkit-transform: rotate(45deg) translate(-8px, -8px);
transform: rotate(45deg) translate(-8px, -8px);
}
3.Use JavaScript to toggle the hamburger menu's open and closed states when the button is clicked:
const hamburger = document.querySelector('.hamburger');
const nav = document.querySelector('.nav');
hamburger.addEventListener('click', () => {
hamburger.classList.toggle('open');
nav.classList.toggle('open');
});
xxxxxxxxxx
h1
{
color:green;
}
body {
height: 100px;
padding: 0;
margin: 0;
overflow: hidden;
}
.navigation {
max-width: 500px;
border-radius: 8px;
background-color: white;
padding-right: 30px;
line-height: 3;
display: flex;
}
.navigationBar {
position: relative;
width: 100%;
height: 100%;
}
.navigationBar::before, .navigationBar::after {
width: 100%;
height: 50%;
background-color: #EAFBFF;
}
*, *::before, *::after {
box-sizing: border-box;
}
.navigationBar.active ul {
width: 420px;
margin-right: 20px;
}
.navigationToggle {
width: 40px;
height: 48px;
padding: 14px 5px;
cursor: pointer;
}
.navigationBar ul {
display: flex;
justify-content: space-between;
list-style: none;
width: 0;
overflow: hidden;
}
.navigationBar:not (.active ) .navigationToggle {
margin-left: -11px;
}
.navigationToggle::after {
margin-top: 10px;
}
.navigationBar.active .navigationToggle::before, .navigationBar.active .navigationToggle::after
{
position: absolute;
top: 52%;
transform: rotate(135deg);
}
.navigationToggle::before, .navigationToggle::after {
content: '';
position: relative;
display: block;
width: 30px;
height: 3px;
background-color: red;
}
.navigationBar.active .navigationToggle::after {
transform: rotate(-135deg);
margin-top: 0;
}
JavaScript Code: HamburgerMenu.js
let navWrapper = document.querySelector('.navigationBar'), navToogler = document
.querySelector('.navigationToggle')
navToogler.addEventListener('click', function(event) {
navWrapper.classList.toggle('active')
});