I implemented the use of "data-target" to ensure that the active link style remains consistent. Is there a way to preserve this style when transitioning between pages from an active link

After referencing the answer to another question, I managed to write code that preserves the style when a link is activated using "data-target". However, the style disappears when navigating to the next page from the active link. For instance, if the original link is "link/sub01.html" but changes to "link/sub01.html&page=2", the style gets lost. I am looking for a solution to maintain the style whenever there is a "data-target" value in the link. Unfortunately, I am not well-versed with scripts and don't know where to make the necessary adjustments. Any assistance would be greatly appreciated.

Please excuse any language discrepancies as I used a translator for this message. Thank you for your understanding!

$(document).ready(function() {
    var url = window.location;
    $('.mainCateBox li a[href="' + 'data-target' + '"]').parent().addClass('active');
    $('.mainCateBox li a').filter(function() {
        return this.href == url;
    }).parent().addClass('active').parent().parent().addClass('active');
});
  • MAIN
  • SUB01
  • SUB02

Answer №1

I have just utilized the index of method to verify that the URL is present at the beginning of the string.

$(document).ready(function() {
    var url = window.location;
    $('.mainCateBox li a[href="' + 'data-target' + '"]').parent().addClass('active');
    $('.mainCateBox li a').filter(function() {
        return (this.href.indexOf(url) === 0)
    }).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">
    .mainCateBox {
        position: relative;
    }

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

    .mainCateBox 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;
    }

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

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

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

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

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


<div id="prdListCate">
    <ul class="mainCateBox">
        <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 №2

Below is an illustration of how to trim a URL to match a data-target. Feel free to test it out. Simply update

var url = window.location;

to

var url = window.location.split('&')[0];

$(document).ready(function() {
    setLink = 'sub01.html&page=2';
    var url = setLink.split('&')[0];
    console.log(url);
    $('.mainCateBox li a[href="' + 'data-target' + '"]').parent().addClass('active');
    $('.mainCateBox 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">
    .mainCateBox {
        position: relative;
    }

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

    .mainCateBox 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;
    }

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

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

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

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

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


<div id="prdListCate">
    <ul class="mainCateBox">
        <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>

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

What is the best approach for retrieving data from an external URL?

After implementing this code: $(document).ready(function() { $.ajax({ type: "POST", url: "http://steamcommunity.com/market/priceoverview/?currency=3&appid=730&market_hash_name=StatTrak%E2%84%A2%20P250%20%7C%20Steel%20Disruption%20%28Facto ...

Caching HTML5 videos in Google Chrome

I am currently in the process of building a website and have successfully added an HTML5 video. However, I encountered an issue when attempting to change the video file in the background for users to upload a new one. Despite updating the video URL, Chro ...

Steps for modifying the values of a "Key-Value" pair within a nested array in MongoDB without inserting a new item

Here is the data I have:- **{ "_id" : ObjectId("5bf8048768d1e82d8bb4a477"), "customer_code" : "c100003", "vm_info" : [ { "instanceId" : "i-0495d75742b839858", "tags" : [ { "Key" : "SIDs", ...

Converting values to hexadecimal in PHP inspired by Javascript's .toString(16)

Is there a way to achieve the same result as JavaScript's .toString(16) in PHP? var n = 200000002713419; console.log(n.toString(16)); When executed, this code returns b5e6211de74b. Is there any equivalent function in PHP to achieve the same output? ...

Storing user responses in an array using jQuery Form

I have developed a form/questionnaire that prompts users with a series of questions. The initial question categorizes users into two groups, either trucks or cars in this scenario. Subsequently, the form delves into specific questions about the chosen vehi ...

`Adjusting function calls based on the specific situation`

On my webpage, I have implemented a tab system where clicking on a tab displays the corresponding content below. This functionality is controlled by a JavaScript/jQuery function called 'changeTab'. Now, I want to set up individual JavaScript fun ...

"An unexpected result was received from an AJAX get request

In my current project using Laravel, I have implemented AJAX to pass the value of a textbox. However, I am facing an issue where it always passes 'R' regardless of the variable passed with AJAX. Below is my code: <div class="form-group"> ...

Experience the ability to dynamically alter an image in a 360-degree

<div style="margin-bottom: 200px"> <a href="#" onclick="cambio()"> sdsadasdas</a> </div> <div id="container"></div> <div id="info"> </div> When I click on a button, I want to change the image dynamica ...

The $scope variable in AngularJS fails to display in the view

Having an issue with a boolean variable that is supposed to switch a DIV from hidden to shown after an action. However, the DIV always remains hidden. Can someone please help me identify what's wrong in the following code: <div class="right" ng-co ...

What is the best way to arrange a MongoDB collection by proximity to geographic coordinates?

Can someone help me with sorting the list of places based on the nearest geo coordinates in this Mongo call? Venues.find({'location.coordinates': { $near : { $geometry : { type : "Point" , coordinates: params ...

Begin the React counter with a starting value of two

Recently, I set up a new React application using the create-react-app command and ran a test with a render counter. Here is the code snippet: import React, { useState } from "react"; let render = 0; export default function App() { const [cou ...

Is there a way to integrate a regular contact form with PHP?

Just bought a web template that only came with a contact form consisting of labels. There was no PHP form included, so need help setting it up... Couldn't add the code here, but uploaded an image screenshot of the contact form: contact form ...

Using Javascript with Selenium to choose an item from a dropdown menu

I'm having trouble selecting an element from a dropdown list and interacting with it. The xpath for the element I'm trying to select from the dropdown is: /html/body/div[1]/div/div[1]/div[1]/div[2]/div/div/div[1]/div[2]/div[1]/div/div/div/div[2] ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

The equal height feature in Bootstrap 4's card-deck is not functioning as expected

I am having an issue with the card-deck property where it is not being applied correctly. The .card-deck class should create a grid of cards that are equal in height and width, and the layout should adjust automatically as more cards are added. Here is th ...

Setting input field value using jQuery depending on the attribute value

Here is an example of an input field: <input data-checkout="card-number" type="tel" placeholder="card number" autocomplete="off" class="input-control" value=""> I am looking to use jQuery to set a value in this field. How can I retrieve the attribu ...

Exploring the World of React JS by Diving into Backend Data

Let's consider an application that consists of three pages: "HomePage" "PrivatePage" "UserManagementPage" In addition, there is a file called "BackendCommunication.js" responsible for handling communication with the backend. "Homepage.js" import Re ...

What is causing these cells in a Google Spreadsheet to be considered equal?

I am currently working on a Google Apps script that interacts with a Google spreadsheet. I'm facing an issue where I need to compare two cells, but they are showing as equal. As part of my code logic, I have a for loop where the comparison is made: ...

Utilize alternating colors from the Material UI palette to enhance the appearance of

Can someone help me understand how to utilize the different color variants in Material UI? For instance, the theme primary color has various options like 100, 200, 300, 400, 500, and so on. How can I access these colors from within my component? I attempt ...

Change in color due to the change in temperature of the

I recently completed a jQuery weather project using data from Wunderground. I am trying to implement a feature where the color of the temperature changes automatically based on whether it is higher or lower, but I am unsure how to incorporate CSS within ...