To create a navbar toggle with JavaScript, you can use the following steps:
- Add a button with a unique id to your HTML that will act as the toggle button.
<button id="toggle-nav">Toggle Nav</button>
- 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>
- Style the
nav
element in your CSS to be hidden by default.
#navbar {
display: none;
}
- 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");
- 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.
+ There are no comments
Add yours