Home > database >  How to create responsive navigation
How to create responsive navigation

Time:06-04

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 >
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>

  </ul>
</nav>

CodePudding user response:

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.

CodePudding user response:

If you read style.display (or in fact style.anything) it reads from the style attribute of the element. <ul > becomes <ul style="display:none"> after the first click (the else part of the condition) and now the if part can evaluate to true. In my opinion you would be much better off with a CSS class and navItems.classList.toggle('the-class-that-handles-visibility').

That said, should the visibility of navItems not be sorted by the media query in the first place? I don't really see a use case for JS here, unless I'm misinterpreting your question.

  • Related