skip to Main Content

I tried to make a responsive nav bar for my website, but when the button to open the hamburger menu is clicked…nothing happens.

Here is the html pertaining to the nav bar

<header>
  <img class="logo" src = "Spotify_Logo.png" alt="logo">
  <nav>
    <a href="#" class="toggle-button">
      <span class="bar"></span>
      <span class="bar"></span>
      <span class="bar"></span>
    </a>
    <ul class="nav_links">
      <li><a href="#">Features</a></li>
      <li><a href="#">About Us</a></li>
      <li><a href="#">Troubleshoot</a></li>
    </ul>
  </nav>
  <a class="cta" href="#"><button>Use Now</button></a>
  
  
</header>

Now here is the CSS and the media screen for the hamburger menu

@media screen and (max-width: 870px){
  .toggle-button{
    display: flex;
  }
 
  .nav_links{
    display: none;
    width:100%;
  }
  .cta{
    display: none;
  }
  .nav_links{
    flex-direction:column;
    align-items: flex-start;
  }
  .nav_links{
    flex-direction:column
  }
  .nav_links li a{
    padding: .5rem 1 rem;
  }
  .nav_links:active{
    display:flex;
  }
}

And finally, the JS

const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks=document.getElementsByClassName('nav_links')[0]


toggleButton.addEventListener('click', -> () {
  navbarLinks.classList.toggle('active')
})

Any help is appreciated!

I have no clue why it isn’t working. I changed the CSS around so it goes for the entire header, that didn’t work. I believe that it might be something with the active tags in the CSS or something wrong in my JavaScript.

2

Answers


    1. there is the syntax error mentioned before
    2. the button is currently not visible because of the media-query (I assume the hamburger is only for mobile, which is assume needs the button)
    3. navbarLinks.classList.toggle('active'); only adds a class called ‘active’ that you don’t have defined.
      I suggest to use navbarLinks.style = "display: flex;" instead. This worked for me.
    Login or Signup to reply.
  1. In the selector of this rule…

    .nav_links:active{
      display:flex;
    }
    

    … "active" needs to be a class in order to react to the class toggle triggered by your JS, i.e. it should not be .nav_links:active , but .nav_links.active

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search