How to Create a Navbar Toggle with JavaScript?

Estimated read time 2 min read

To create a navbar toggle with JavaScript, you can use the following steps:

  1. Add a button with a unique id to your HTML that will act as the toggle button.
<button id="toggle-nav">Toggle Nav</button>
  1. Add a nav element with a unique id that will contain your navigation links.
<nav id="navbar">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>
  1. Style the nav element in your CSS to be hidden by default.
#navbar {
  display: none;
}
  1. In your JavaScript, select the toggle button and navbar elements using their unique ids.
let toggleButton = document.getElementById("toggle-nav");
let navbar = document.getElementById("navbar");
  1. Add an event listener to the toggle button that will toggle the display of the navbar when the button is clicked.
toggleButton.addEventListener("click", function () {
  if (navbar.style.display === "none") {
    navbar.style.display = "block";
  } else {
    navbar.style.display = "none";
  }
});

This code will make the navigation links appear and disappear whenever the toggle button is clicked.

You can further enhance the toggle functionality by adding CSS transitions or animations for a smoother user experience.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply