document.addEventListener("DOMContentLoaded", () => {
let menuBtn = document.querySelector("#menu-button");
let menu = document.querySelector("#menu");
let menuItems = menu.getElementsByTagName("li");
menuBtn.addEventListener("click", e => {
if (e.target.innerText === ("✕")) {
e.target.innerText = "☰";
[...menuItems].forEach(item => item.style.display = "none");
} else if (e.target.innerText === "☰") {
e.target.innerText = "✕";
[...menuItems].forEach(item => item.style.display = "block");
}
});
});
header {
width: 100%;
height: 100px;
}
#menu {
display: flex;
flex-direction: row;
margin: 0 auto;
justify-content: space-around;
font-size: 2rem;
}
#menu-button {
display: none;
}
li {
list-style-type: none;
}
a {
text-decoration: none;
color: rgb(0, 0, 0);
}
@media screen and (max-width: 1050px) {
#menu {
flex-direction: column;
width: 100%;
height: 100%;
}
#menu li {
padding: 1.5rem;
display: none;
}
#menu-button {
display: block;
font-size: 3rem;
cursor: pointer;
outline: none;
border: none;
}
}
<header>
<nav>
<button id="menu-button">☰</button>
<ul id="menu">
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
</header>
It's a simple nav menu with desktop-first approach that uses flexbox.
- Viewport is less than 1050px and therefore shows hamburger button
- Hamburger button is clicked to show menu in dropdown form. Hamburger button changes to "X".
- "X" is clicked. The JS code changes all
lielements todisplay: none - PROBLEM: Viewport is increased beyond breakpoint of 1050px. Since
lielements were changed todisplay: none, menu is not shown.
Would appreciate suggestions on how to address this.
Also, smaller but nagging issue.
- Viewport is less than 1050px and therefore shows hamburger button
- Hamburger button is clicked to show menu in dropdown form. Hamburger button changes to "X".
- Viewport is increased beyond breakpoint of 1050p and then back below breakpoint. Since all
lielements were set todisplay: blockin JS code, the dropdown menu appears. I'd like to make it so that the hamburger icon appears whenever viewport size is decreased.
Thanks for all and any help!