Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create responsive navigation

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading