How to add active class in menu using jquery

How-to-add-active-class-in-menu-using-jquery

Add active class to a navigation menu item based on URL using jQuery

HTML Code

<nav>
	<ul>
		<li><a href="/">Home</a></li>
		<li><a href="/about/">About</a></li>
		<li><a href="/clients/">Clients</a></li>
		<li><a href="/contact/">Contact Us</a></li>
	</ul>
</nav>	

jQuery Code

<script>
$(function () { 
	var url = window.location.pathname; 
	var activePage = url.substring(url.lastIndexOf('/') + 1); 
	$('#menu-section li a').each(function () { 
		var linkPage = this.href.substring(this.href.lastIndexOf('/') + 1);
 
                if (activePage == linkPage) { 
		$(this).parent().addClass('activemenu'); 
	}
    });
}) 
</script>
Learn Tutorials Point
We Well organized and easy-to-understand Interactive tutorials With lots of examples of how to use Tutorials WordPress, PHP, Bootstrap, Bootstrap 4, HTML, CSS, AJAX, jQuery, Woocommerce, Post, Database, Javascript, Theme, Responsive, Templates.
Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact us

Fill in the form below or give us a call and we'll contact you. We endeavour to answer all enquiries within 24 hours on business days.