I utilized the "data-target" attribute to ensure the active link retains its style. Is there a way to preserve the style when navigating away from an active link?

Can someone assist me with this re-upload?

I need help tweaking my code to maintain style when navigating between pages using the "data-target" attribute. Currently, the style is being lost when moving from the original link (e.g., "link/sub01.html") to a modified link (e.g., "link/sub01.html&page=2"). I want the style to persist whenever there's a "data-target" value in the link. However, I'm not very familiar with scripting and don't know where to make the necessary adjustments. Any guidance would be greatly appreciated.

Please excuse any language discrepancies as English isn't my primary language, so I'm relying on a translator tool. Thank you for your understanding!

$(document).ready(function() {
    var url = window.location;
    $('#CateList .CateBox li a[href="' + 'data-target' + '"]').parent().addClass('active');
    $('#CateList .CateBox li a').filter(function() {
        return this.href == url;
    }).parent().addClass('active').parent().parent().addClass('active');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style type="text/css">
    .CateBox {
        position: relative;
    }

    .CateBox:after {
        display: block;
        content: "";
        clear: both;
    }

    .CateBox li {
        position: relative;
        display: inline-block;
        width: 180px;
        height: 34px;
        float: left;
        line-height: 34px;
        text-align: center;
        border: 1px solid #333;
        border-bottom: 0;
        border-radius: 15px 15px 0 0;
        box-sizing: border-box;
        overflow: hidden;
        background: rgba(51, 51, 51, 0);
        transition: all .35s;
    }

    .CateBox li a {
        display: block;
        text-decoration: none;
        background: rgba(51, 51, 51, 0);
        transition: all .35s;
    }

    .CateBox li:hover {
        background: rgba(51, 51, 51, 1);
    }

    .CateBox li:hover a {
        color: #fff;
    }

    .CateBox li.active {
        background: rgba(51, 51, 51, 1);
    }

    .CateBox li.active a {
        color: #fff;
    }
</style>


<div id="CateList">
    <ul class="CateBox">
        <li data-target="index"><a href="index.html">MAIN</a></li>
        <li data-target="sub01"><a href="sub01.html">SUB01</a></li>
        <li data-target="sub02"><a href="sub02.html">SUB02</a></li>
    </ul>
</div>

Answer №1

Without actually testing your code, it appears that the issue may be related to the parameters or query string in your URL.

You can use href.split('?')[0] to isolate the URL and exclude the query string for testing purposes.

In addition, I suggest a more straightforward approach:

<nav>
    <ul>
        <li>
            <a href="/" title="">Home</a>
        </li>
        <li>
            <a href="/Contact/" title="">Contact</a>
        </li>
    </ul>
</nav>
// Function for setting active navigation state
let mainNav = document.querySelectorAll('nav ul li a');

for (let i = 0; i < mainNav.length; i++) {
    if (mainNav[i].href.split('?')[0] === window.location.href.split('?')[0]) {
        mainNav[i].classList.add('active');
    }
}

This script is written in Vanilla JS, but you could easily convert it to jQuery if needed :)

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

How to pass a prop from Nuxt.js to a component's inner element

I've created a basic component: <template> <div id="search__index_search-form"> <input :bar-id="barId" @keyup.enter="findBars()" type="text" :value="keyword" @input="updateKeyword" placeholder="Search for a b ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Reacting with Angulatory: Response heads are not being transferred in applications

I'm facing an issue where the cookie containing my authentication token doesn't get passed along with my requests. After authenticating in Chrome, the response sets the cookie correctly, but it's not included in subsequent requests. This is ...

What is the technique for choosing the parent's ID with jQuery?

When a user clicks on any team, I need to retrieve the parent's parent ID. For example, if someone clicks on a Premier League Team, I want to store the ID 2 in a variable called league_id. Here are my attempts so far: Using Closest Method $('u ...

JavaScript click or text-to-speech

Currently, I am working on a web application that is designed to automatically read text. Below is the code snippet that I am using: function hablalo() { var palabra = new SpeechSynthesisUtterance('Casilla 6 turno E18'); palab ...

The menu was intended to be hidden when the mouse is moved away, but it actually hides

I'm facing an issue with my button and menu functionality. Even though I have coded the menu to hide itself when the mouse leaves, it hides before the mouse even goes over it. Any suggestions on how to resolve this? function showMenu() { var menu ...

Failure of PrimeNG Autocomplete dropdown to adjust position

My experience with the PrimeNG Autocomplete plugin resulted in some conflicts. When using this style, the autocomplete drop-downs are positioned downward. Image description goes here https://i.sstatic.net/VZmAk.png If anyone knows how to resolve this is ...

There appears to be an issue with reading the property 'toLowerCase' of an undefined element, and I'm having trouble identifying the error

The variables I have initialized (globally): var audio; var LANGUAGE; var audioArray; var MEDIAARRAY; var WORDS; var SOUNDARRAY; This specific line is causing the error: var audioId = MEDIAARRAY.audio.lowercase.indexOf(exObject['exerciseGetWordInpu ...

Utilizing a custom filter for object manipulation within Vuetify's v-autocomplete

When using vuetify v-autocomplete with an object where the object consists of Key-Value pairs, the search functionality is based on the item-text. In my example, I am displaying the object as {1200-Chloride Systems}. Is it possible to make the search funct ...

What is the best way to showcase a category on the thumbnail of a WordPress post?

Hey everyone, I hope you're all having a great day! I need some assistance with a slider I'm creating on my WordPress site. I can't seem to figure out how to display the category of each post that appears in the slider and have it stand out. ...

AJAX Mailer with Enhanced Attachment Functionality using Bootstrap Extension

I have successfully written a script for sending emails. It randomly selects an email and sends it with random values. Now, I want to add an option to send multiple images - select one randomly and attach it to the email. Using bootstrap, I found this plu ...

Moving from one section to the next within a web page

I am looking to add animation to my web app. When clicked, I want to move only the ID table column from one div to another div while hiding the other column. However, I am struggling with figuring out how to animate the movement of the ID column (from the ...

Heroku encounter an H14 error - "the absence of running web processes"

An H14 error occurred during deployment on Heroku. Here is my Procfile: web: gunicorn -w 4 -b 0.0.0.0:$PORT -k gevent main:app Error log on Heroku: 2017-01-23T10:42:58.904480+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method ...

What is the process for incorporating a scrolling feature into my HTML page?

I need to display the following content on my website: What code do I need to add in order to achieve this? I tried using the code snippet below but it did not work as expected: <td nowrap align="left" style="word-wrap: break-word"><pre style="w ...

Leveraging the power of axios.all for dynamic operations

Is there a way to efficiently reuse the same Vue-component for both editing and creating new users? While working with vue-router, I have implemented a beforeRouteEnter method to fetch data via API. Depending on whether an ID is set in the URL parameter, ...

How can I align the navigation bar in the center using Bootstrap?

Let's discuss the code snippet provided below. I am looking to use Bootstrap to center this dropdown menu on the left side of the screen. Here is the screenshot for reference: . Any suggestions on how I can achieve this? Also, I would like to know h ...

Footer at the bottom and a sticky navigation bar

I have experimented with various CSS guides in order to place the footer at the bottom of the page, and I have found the example below to be the simplest method. html, body, #root { height: 100%; } #root { display: flex; flex-direction: column; } ...

Varying ng-click depending on another value

When a user uploads their own photo, I resize the image, add an ng-click attribute, compile it, and append it to a new element. This process is triggered once upon photo upload: var myElement = angular.element(image); // getting the image myElement.attr( ...

Finding a date from a calendar with a readonly property in Playwright

Just starting out with the playwright framework after working with Protractor before. I'm trying to figure out the correct method for selecting a date in Playwright. selector.selectDate(date) //having trouble with this ...

Where could I be missing the mark with AngularJS?

After following some tutorials, I managed to create my first test app. However, it doesn't seem to be working properly. The main objective of the app is to extract product information from a JSON file and display it using ng-repeat. Here are the rele ...