Adding active class to active navigation with jQuery

Code snippet to add active class to active navigation menu.
Share:
1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...
Adding active class to active navigation with jQuery
Table Of Content:
Related Article
class active in navigation
jQuery(function() {
	if ( window.location.pathname == '/' ){
    		jQuery('.home_link').addClass('active');
	} 
	else {
		jQuery('.main-menu_classes a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
	}
});

Short explanation of the code "Adding active class to active navigation with jQuery"

I added an active class to the HOME or HOME menu (which I have marked with the home_link class) specifically for the homepage only. If the browser opens a page other than the homepage, the active class will be added to the menu according to the link we are currently opening.

Suppose we open the ABOUT page, then the /about/ link will be added to the active class .

An example of using this script I used when converting the https://www.ibeemusic.id website which previously used Elementor, then converted it using Oxygen Builder.

Additional Notes:

I found difficulties when adding the active class to the taxonomy, the solution was using the code from https://stackoverflow.com/a/34547305 as below:

    jQuery(function($) {
     var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
     $('ul a').each(function() {
      if (this.href === path) {
       $(this).addClass('active');
      }
     });
    });

Leave a Reply

Your email address will not be published.

Related Article

Adding Meta Author
Adding Meta Author in WordPress
Navigation Menu
Code (Function) to bring up the menu list in WordPress
Adding CLASS After Page Load
This javascript code snippet is to add a class to an element after the page is finished loading the DOM.
COMPLETE PACKAGE OF WEBSITE DESIGN & DEVELOPMENT
Digitalizer offers website design & development services for company profiles, online shops, event organizers, educational institutions or other fields. You don't need to think about domains, web hosting / servers, DNS, email, design, development, security and other technical issues. Just prepare your website content, we do the rest.
All website design & development packages include 1 year maintenance!
Free Consultation
Back to top
cross