Home > Software design >  Why doesn't my script open my dropdown menu?
Why doesn't my script open my dropdown menu?

Time:07-12

I have this snippet of code for my personal website that uses JavaScript to activate the Hamburger menu. However, it does not work and I am not sure why. The other JS in my code works no problem.

Here is the Code:

var navbar = document.getElementById(".navbarNav");

function hideShow() {
  if (navbar.style.display == "block") {
    navbar.style.display = "hideShow()";
  } else {
    navbar.style.display = "block";
  }
}
<nav >
  <div >
    <a  href="index.html">Edward Wynman</a>
    <button  type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="true" aria-label="Toggle navigation">
  <span ></span>
</button>
    <div  id="navbarNav">
      <ul >
        <li >
          <a  aria-current="page" href="index.html">Home</a>
        </li>
        <li >
          <a  href="about.html">About</a>
        </li>
        <li >
          <a  href="courses.html">Courses</a>
        </li>
        <li >
          <a  href="projects.html">Projects</a>
          <li >
            <a  href="/Files/EddieReume.pdf">Resume</a>
          </li>
          <li >
            <a  href="contact.html">Contact</a>
          </li>
      </ul>
    </div>
  </div>
  </div>
</nav>

Let me know if you need anything else like the CSS or other code.

CodePudding user response:

Looking at your markup, are you trying to use Bootstrap? In your code I can see data attributes such as data-bs-toggle which indicate you are. If so, make sure you are using the Standard menu Menu opened

Your code working can be seen here

If you want to know how to create a custom bit of JS to trigger this, please comment and I'll update my answer accordingly.

CodePudding user response:

Final Answer

var navbar = document.getElementById("navbarNav");
    function hideShow() {
      console.log("click")
      if (navbar.style.display == "block") {
        navbar.style.display = "none";
        console.log("disapper")
      } else {
        navbar.style.display = "block";
        console.log("visible")
      }
    }

CodePudding user response:

when you are using getElementById() don't use .(dot) to defined the Id Attribute.

var navbar = document.getElementById("navbarNav"); 

// var navbar =document.getElementById("navbarNav"); or
// let navbar=document.querySelector('#navbarNav'); this method also work.

function hideShow() {
  if (navbar.style.display == "block") {
    navbar.style.display = "hideShow()";
  } else {
    navbar.style.display = "block";
  }
}
  • Related