How to Create an Active Menu with jQuery?

Estimated read time 2 min read

To create an active menu with jQuery, you can add a class to the currently selected menu item using the addClass() method. Here’s an example:

HTML code:

<nav>
	<ul>
		<li><a href="#home">Home</a></li>
		<li><a href="#about">About</a></li>
		<li><a href="#services">Services</a></li>
		<li><a href="#contact">Contact</a></li>
	</ul>
</nav>

In this example, we have a simple navigation menu with four links.

jQuery code:

$(document).ready(function(){
	var navLinks = $("nav a");

	navLinks.click(function(){
		navLinks.removeClass("active");
		$(this).addClass("active");
	});
});

In this example, we use the $() function to select all the links in the navigation menu, and we store them in the navLinks variable. We use the click() method to listen for clicks on the links, and when a link is clicked, we remove the “active” class from all the links using the removeClass() method, and then add the “active” class to the clicked link using the addClass() method.

Finally, we add the “active” class to the first link by default:

$(document).ready(function(){
	var navLinks = $("nav a");

	navLinks.first().addClass("active");

	navLinks.click(function(){
		navLinks.removeClass("active");
		$(this).addClass("active");
	});
});

In this example, we use the first() method to select the first link in the navigation menu, and we add the “active” class to it using the addClass() method. This ensures that one link is always active by default when the page loads.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply