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
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.In the selector of this rule…
… "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