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...
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. Required fields are marked *

Related Article

Fade-In Effect on Window Load
Javascript code for fade-in effect on window load
Disable AOS in Oxygen Builder Editor
CSS for disable AOS in Oxygen Builder
OpenStreetMap and Leaflet.js
Snippets code to use OpenStreetMap and Leaflet.js
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