0

I was making a responsive navbar but doesn't respond when clicked. I definitely think my javascript is at fault here. here is the below: -

const bars = document.querySelector('#bars');

bars.addEventListener('click', () => {
  const nav = document.querySelector('.navbar');
  nav.classList.toggle('show');
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet"/>
<nav>
  <ul class="navbar">
    <li> <a href="#">HOME</a> </li>
    <li> <a href="#">SERVICES</a> </li>
    <li> <a href="#">PRODUCTS</a> </li>
    <li> <a href="#">BLOG</a> </li>
    <li> <a href="#">CONTACT</a> </li>
  </ul>
  <i class="fa fa-bars" id="bars"></i>
</nav>
SMAKSS
  • 9,606
  • 3
  • 19
  • 34
  • Your code is working fine, what is your problem? – SMAKSS Jun 29 '20 at 07:54
  • I think it would be better to consider: https://stackoverflow.com/questions/68048470/changing-height-of-a-div-using-a-button-on-small-screen-only. I used this concept to build the **responsive navbar** for the website: https://monicamp.com. You may choose the pure ```JavaScript``` or ```jQuery``` method to implement it. – Ocean Aug 01 '21 at 18:23

1 Answers1

1

Your JavaScript could work fine depending on the HTML and CSS that go with it. Here's an example of HTML and CSS that your existing code can support.

If you compare this to what you have, you should be able to see where to change your HTML/CSS (or your script) to make them work together the way you want.


BTW, if it's not already clear to you, your script says:

When the user clicks the element with the id bars...

  • find the first element with the class navbar
  • Add the class show to it if it doesn't have it already, or remove the class show from it if it does have it already.

const bars = document.querySelector('#bars');

bars.addEventListener('click', () => {
  const nav = document.querySelector('.navbar');
  nav.classList.toggle('show');
});
.navbar {
  display: none;
  width: 200px;
  height: 50px;
  background-color: blue;
}

.show {
  display: block;
}
<div>
  <button id="bars">Bars</button>
</div>
<div class="navbar"></div>
Cat
  • 4,141
  • 2
  • 10
  • 18