Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
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>

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

If you read style.display (or in fact style.anything) it reads from the style attribute of the element. <ul class="nav-items"> becomes <ul class="nav-items" 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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!