Activate the parent navigation link when on sub-pages

I want to ensure that the parent navigation item is highlighted when a user is on a child page based on the URL.

For example, if the user is currently viewing foo1-child and the parent is foo1, I need to apply the active class to Foo 1:

http://foo.com/foo1/foo1-child.html

NAV:

<ul class="main-nav">
  <li><a href="/foo.com/foo1.html">Foo 1</a></li>
  <li><a href="/foo.com/foo5.html">Foo 5</a></li>
</ul>

While adding an active class to links in the navigation is straightforward by comparing the href attribute with the URL, how can I specifically look for a matching anchor link name or similar identifier within the URL?

Current JS

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    if ($this.attr('href').indexOf(location.pathname) !== -1) {
      $this.addClass('active');
    }
  });

Answer №1

To make it function properly, remove the ".html" from the end of both links and compare the shortened href with the location.

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    var loc = location.
    if (location.pathname.replace(/\/[^\/]*\.html$/, '').startsWith($this.attr('href').replace(/\.html$/, ''))) {
      $this.parent().addClass('active');
    }
  });

For a demonstration, visit this link here. Keep in mind that the pathname used is artificial as jsfiddle lacks the required prefixes in its path, but the concept remains valid.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve JSON and HTML in an AJAX request

I have multiple pages that heavily rely on JavaScript, particularly for sorting and filtering datasets. These pages typically display a list of intricate items, usually rendered as <li> elements with HTML content. Users can delete, edit, or add item ...

React displaying an error indicating that the setTimeout function is undefined?

While attempting to integrate the XTK library with React, I encountered an issue where it kept throwing an error stating that the setTimeout function is not a valid function. Surprisingly, my code appears to be flawless and works perfectly fine when used d ...

Issue with white spaces in footer content in Chrome browser

Currently in the process of developing a website and encountering a strange bug that only seems to be affecting Chrome. Despite having the latest version of Chrome, it appears to be an issue that was prevalent in older versions (v18 - v20). The problem is ...

Inserting data with special characters from an Ajax POST request into a database

I am facing an issue with my form that contains text inputs. When I use an ajax event to send the values via POST to my database PHP script, special characters like ' " \ cause a problem. If the string contains only numbers/letters and no special ...

What is the best way to incorporate font-awesome icons into a Rails view?

I'm struggling to incorporate font-awesome icons in my Rails view. I had a static standalone HTML code snippet that I added into the Rails view: <span class="icon-white"> <a href="https://twitter.com/xyz"> <i class="icon icon-tw ...

Error: The value being evaluated in document.getElementById(x).style is not an object and is not supported

Desired Outcome for my Javascript: I am working with a div that includes an "onmouseover='getPosition(x)'" attribute which can be dynamically added and removed through my javascript by clicking a specific button. The function 'getPosition() ...

Error in Typescript for a function that accepts several types of lists - property does not exist on the interface

In my project, I have defined three interfaces: a base interface and two others that extend the base one with children as properties. One of the interfaces includes 'valueType' while the other includes 'returnType'. Here is how they are ...

The notification panel pop-up box keeps moving away from the right side

I'm currently in the process of creating a straightforward vertical notification panel, similar to the one seen on Stack Overflow. However, I've encountered an issue where the pop-up is not staying positioned correctly to the right side. It behav ...

real-time update of gauge value from soap

I am trying to update the value shown in my justgage widget with the value returned from $("#spanrWS_Measured").text(data[0]);. The current value is 123. Any assistance would be greatly appreciated. See the complete code below. <script src="scripts/r ...

Angular 2 click event with changing function name

Even though this question seems simplistic, I'm having trouble figuring it out. As someone new to Angular 2, I've tried various combinations of {}, [], and () brackets to make the following work: <button (click)="this.action">Click me</ ...

Efficient State Management with React-Redux for Streamlined HTTP Requests

In the process of developing a React-Redux application, I have encountered a situation where I need to display a cancel button while a specific HTTP request is ongoing. Upon successful execution of the request, the UI should display the results. If the use ...

Is there a way to consistently substitute a specific path parameter with a different value within node.js?

Snippet of my coding: router.get('/name/:name/height', (req,res) => { ... } router.get('/name/:name/weight', (req,res) => { ... } router.get('/age/:age/height', (req,res) => { ... } router.get('/ag ...

determine the color of the pixel at the top left corner of a jpg image

If we were given a specific URL, for instance, "//upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg", how can we use javascript (specifically jQuery or Angular) to obtain the top left coordinates (or any (x,y) coordinates) of this image? Just to clarify, ...

Retrieve data from a URL using jQuery's .get method and iterate over each element using

After successfully retrieving the HTML using the jQuery get function and displaying it, I now have a question. How can I use the .each jQuery function to iterate through each div contained within the retrieved data? Specifically, I want to target a single ...

Guide to connecting a different HTML page to a thumbnail image using jQuery

let newColumnBlock = $('<div class="col-md-2">'); let newImagePoster = $('<img>'); let newSelectButton = $('<a href="secondPage.html"><button class="selectButton"></button></a>'); let movie ...

View the image without needing to upload it

Can you display an image from an input type="file" on a page without actually uploading it to the server? Is there a way to copy the image into a location that the script can access in order to achieve this? It doesn't matter if it loads after a refr ...

Fast method or tool for generating a detailed CSS element list from deeply nested elements

I have been using Chrome dev tools to work on a code base that was not created by me. There are numerous deeply nested elements scattered throughout the code. I find myself having to manually search through the HTML structure in order to select them with ...

I would appreciate it if someone could clarify how the rendering process occurs in React in this specific scenario

let visitor = 0; function Mug({name}) { visitor = visitor + 1; console.log(name, visitor); return <h2>Coffee mug for visitor #{visitor}</h2>; } return ( <> <Mug name={"A"}/> <Mug name={"B&qu ...

Button-click scrolling is our featured feature!

One interesting feature on my website is a button (within a div-element) located in the bottom-right corner. I am now looking to enhance this by adding a jQuery function that enables the user to scroll down the page incrementally simply by clicking and hol ...

Trouble with Buttons not appearing on Datatables.net

Despite numerous attempts and thorough testing, I am unable to get buttons to appear on a datatables.net table. I have diligently added all the necessary scripts for buttons and followed every initialization example provided on datatables.net with no succe ...