Apply an active navigation class depending on the current URL in the session

Is there a way to dynamically add an .active class (font-weight:700;) to the active pages navigation menu based on the category in the URL?

The system url is constructed using session and category parameters.

For example, the homepage for logged-in users is located at

And the navigation menu links are structured as follows:

  • Cat 1 -
  • Cat 2 -

If anyone can guide me on how to extract the category from the URL and apply the .active class accordingly, it would be greatly appreciated. Thank you!

<div id="SbCatMenu">
<dl id="dlCatLvl1" class="clsCatLvl1 clsOffCat1">
<dd class="clsCatTree1 clsCTree1" id="CatImg1"><a href="../OeCart/OeFrame.asp?PmSess1=1338988&amp;SXREF=1">Apparel<span class="clsCatOffCount"> 15</span></a></dd>
<dd class="clsCatTree1 clsCTree1" id="CatImg2"><a href="../OeCart/OeFrame.asp?PmSess1=1338988&amp;SXREF=2">Events<span class="clsCatOffCount"> 23</span></a></dd>
...
...
</dl>

</div>

I've attempted the following JavaScript code without success:

$
(function(){

//this returns the whole url

  var current = window.location.href;
   console.log(current)

  //this identifies the list you are targeting

  $('#dlCatLvl1 dd a').each(function(){
    var $this = $(this);
    console.log(this)

  // if the current path is exactly like this link, make it active

    if($this.attr('href') === current){        
       $this.css('color', 'red');
    }
     })   
});

Answer №1

Focus on matching instead of comparing values:

if(current.match($this.attr('href').replace('..', '') !== null){     
  $this.css('color', 'red');
}

Since all your href values begin with ../OeCart/OeFrame.asp[...]and your browser's href always starts with the full url http://www.your.domain.de/[...].

EDIT: The beginning of your href-values contains dots, so remove them.

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

Indicator malfunctioning on Carousel feature

I created a carousel containing six photos, but I am encountering an issue with the carousel indicators below. The first three indicators work correctly – when clicked, they take me to the corresponding slide (e.g., clicking the 1st indicator takes me ...

Retrieve calling image from array on rollover

Currently working on a website where I want to incorporate multiple rollovers using the same base image (distributed black pixels all over the page to create a popup effect). I decided that the best way to approach this is to use an array with all the ro ...

Unlock the parent of an unnamed iframe

Here's a scenario: <div id="parent"> <iframe....></iframe> </div> If I had the above structure, I could use window.parent.document.getElementById('parent').innerHTML to access it. However, my current situation is di ...

Adjust the width of a div in Angular 6 based on a specified condition

I need to adjust the width of a div based on certain conditions. <div [ngStyle]="'width': selectedTab =='Home' ? '50%' : '100%'"> </div> The currently selected tab is stored in "selectedTab". There ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...

An individual in a chat App's UserList experiencing issues with incorrect CSS values. Utilizing Jquery and socketio to troubleshoot the problem

Currently, I am testing a new feature in a chat application that includes displaying a user list for those who have joined the chat. The challenge is to change the color of a specific user's name on the list when they get disconnected or leave the cha ...

Tips for storing dynamically added row data from an HTML table to a (csv/txt) file using C#

I am dynamically adding new rows to a table named "newDataTable" using the JavaScript function below: function addRow() { //add a row to the rows collection and get a reference to the newly added row var table = document.getElemen ...

Step-by-step guide on validating a user in Joomla using AJAX and jQuery

Is there a way to authenticate a user in Joomla through an AJAX call? I want to implement an error effect if the login is incorrect and redirect the user upon successful authentication. I am specifically interested in using JQuery's .ajax API for thi ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Setting default property values in a React component using Typescript

   Is there a way to define default property values in React components when using Typescript? I came across a post on SE suggesting the use of a static class variable called defaultProps with key-value pairs for properties. However, this method didn&a ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Determining the clicked node in a JavaScript environment

There are multiple spans with labels. <span class="viewEdit">View and edit class one.</span> <span class="viewEdit">View and edit class two.</span> <span class="viewEdit">View and edit class three.</span> <span clas ...

What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters? HTML <input type="number" name="cost" value= ...

When attempting to display a JSON array, a variable defined as numeric transforms into NaN

I'm attempting to split a JSON array into three-column Bootstrap rows using the code below. My approach involves increasing a numeric variable to 3, adding a new row div, and then setting it back to 1. However, I am encountering an issue where the va ...

Avoiding the collapse of the Bootstrap 4 navbar

Having trouble with the navbar collapsing on itself? The issue seems to occur around 1280px window size, but works fine when the window is wider or narrower. https://www.bootply.com/AcsaaqReAL .navbar-custom { background-color: #333333; border- ...

Ways to verify if an image is captured from the device's camera using HTML5

I'm facing a unique challenge that may be considered an edge case. The situation is that I am currently in the process of developing a website that functions as a mobile application (similar to a mobile-first website). In order to achieve this, I have ...

Animating a gradient within an SVG element following along an SVG path

I successfully created an SVG egg and animated a path while adding a gradient, but I am facing an issue. The linear gradient goes from top to bottom, but I want the dark color at 0% and the light color at 100%. Essentially, I want the gradient to follow th ...

Using angular.js variables in the script tag: A step-by-step guide

Currently, I am working on a project that involves displaying elements on a view using Angular.js and attempting to connect these DOM elements using jQuery connections. While the elements are being displayed correctly, I am encountering an issue when tryin ...

Entry Points for Logging In

After stumbling upon this pre-styled Material UI login page example, I decided that it was exactly what I needed. However, I ran into an issue when trying to figure out how to store the username and password values. Whenever I try to use 'State' ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...