How to add css-class active for menu items by using just javascript code?
(function($){ $(function() { // Document Ready activeMenu(); }); // Functions function activeMenu() { var url = window.location.pathname, // create regexp to match current url pathname and remove trailing slash if present. urlRegExp = new RegExp(url.replace(/\/$/,'') + "$"); // now grab every link from the navigation $('.menucss a').each(function(){ // Swap to your menu CSS Class or ID // and test its normalized href against the url pathname regexp if(urlRegExp.test(this.href.replace(/\/$/,''))){ $(this).addClass('current'); // Add CSS Class 'current' to active link tag } }); } })(jQuery);
Replace the “.menucss” with yours.
<ul class="menucss"> <li><a>Home</a></li> <li><a>About</a></li> <li><a>Contact</a></li> </ul>
That’s all!