Issue
I am trying to create menu that will appear under the navbar, I'd like the button and logo be spaced between and I want the items to appear below. How can I achieve this? Now I am having 3 items in row instead of the nav items appearing below. My code seems to be buggy and I have to press twice on button in order for anything to happen. Why is this happening?
const btn = document.querySelector('button');
btn.addEventListener("click", () => {
const navItems = document.querySelector('.nav-items');
if (navItems.style.display == "none") {
navItems.style.display = "block"
} else {
navItems.style.display = "none";
}
})
nav {
display: flex;
align-items: center;
}
.nav-items {
margin-left: auto;
list-style: none;
display: flex;
}
li {
padding: 10px;
}
button {
display: none;
}
@media only screen and (max-width: 900px) {
.nav-items {
display: none;
}
button {
display: block;
margin-left: auto;
}
}
<nav>
<h2>Logo
</h2>
<button>
Toggle Mobile
</button>
<ul class="nav-items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</nav>
Solution
The first time it runs, navItems.style.display
doesn't equal "none", it's empty, so the show logic doesn't work.
You'd be better off reversing the logic:
if (navItems.style.display == "block") {
navItems.style.display = "none";
} else {
navItems.style.display = "block"
}
To get you started on the layout, add flex-wrap: wrap
to nav
, and width: 100%
to .nav-items
.
Answered By - Geat
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.