if path name is different but parent nav should be active in jquery

If path name is different but parent nav should be active in jQuery

As a web developer, I have come across situations where I needed to highlight the current page in the website's navigation menu. This is especially important in websites with multiple pages or sections, as it helps users know where they are on the site.

One common challenge in achieving this is when the path name of the current page is different from the parent navigation item. For example, if the parent item is "About Us" with a path name of "/about-us", but the current page has a path name of "/about/team", we need to ensure that the "About Us" item is still highlighted.

To accomplish this in jQuery, we can use a combination of the .split() and .indexOf() methods. Here's how:

var path = window.location.pathname; // get the current path name
var parentNavItem = $('.nav-item.dropdown'); // get the parent navigation item

if (path.split('/')[1] === 'about-us' || path.indexOf('about') !== -1) {
  parentNavItem.addClass('active'); // add the active class to the parent nav item
}

In the above code, we first get the current path name using window.location.pathname. We then select the parent navigation item using jQuery and save it to a variable.

The next line is where we check if the current page matches the parent item. We do this by splitting the path name into an array using .split() and checking if the second item (index 1) matches the parent path name or if the path name contains the word "about" using .indexOf().

If the current page matches the parent item, we add the active class to the parent navigation item using .addClass().

Another way to accomplish this is by using regular expressions. Here's an example:

var path = window.location.pathname;
var parentNavItem = $('.nav-item.dropdown');

if (/about(-us)?/.test(path)) {
  parentNavItem.addClass('active');
}

In this code, we use a regular expression to test if the path contains the word "about" followed by an optional "-us". If it matches, we add the active class to the parent navigation item.

Both of these methods should work in most cases, but it's always a good idea to test thoroughly and make adjustments as needed.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe