I am trying to code a burger menu that will change symbol from "-" to "x" on click and also show menu.
I'm done with the first part. The symbol is changed / toggled on click but I can't figure out how to display the menu.
This is working code I have
const menuButton = document.querySelector(".menu-button");
let showMenu = false;
menuButton.addEventListener("click", toggolmenu);
//function
function toggolmenu() {
if (!showMenu) {
menuButton.classList.add("close");
showMenu = true;
} else {
menuButton.classList.remove("close");
showMenu = false;
}
}
What I need to do is that when you click on ".menu-button" it will change from this:
<div class="menu-body">...</div>
to this:
<div class="menu-body show-menu-body">...</div>
Any ideas? Thank you in advance for your time
Similar to what you already have, toggle a class to the Menu element too, i.e. by using Element.classList.toggle():
const elMenuBtn = document.querySelector(".menu-button");
const elMenu = document.querySelector(".menu-body");
const toggleMenu = () => {
elMenuBtn.classList.toggle("close");
elMenu.classList.toggle("show-menu-body");
};
elMenuBtn.addEventListener("click", toggleMenu);
Here's an example without JavaScript at all, just a checkbox and CSS :checked pseudo.
To than target and style the next elements use the General Sibling Combinator selector ~
/* QuickReset */ * {margin:0; box-sizing:border-box;}
#menu-toggler {
position: absolute;
opacity: 0;
}
#menu-btn {
position: fixed;
z-index: 101;
padding: 10px;
font-size: 2em;
cursor: pointer;
}
#menu-btn:before {
content: "\2630";
}
#menu {
position: fixed;
z-index: 100;
top:0;
bottom: 0;
left: 0;
min-width: 200px;
transition: 0.5s;
transform: translateX(-100%);
padding-top: 4em;
background: #f48024;
}
/* CHECKED STATES */
#menu-toggler:checked ~ #menu-btn:before {
content: "\2715";
}
#menu-toggler:checked ~ #menu {
transform: translateX(0);
}
<input id="menu-toggler" aria-controls="menu" type="checkbox">
<label id="menu-btn" for="menu-toggler" aria-controls="menu-tog" aria-label="Toggle Menu"></label>
<nav id="menu">
<ul>
<li>Lorem</li>
<li>Ipsum</li>
<li>Dolor</li>
</ul>
</nav>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With