Keep the color of the clicked link consistent

I've been experimenting with keeping the color of a link when clicked, not just while the mouse is over it (so that if the mouse moves away from the link, the color will stay).

For example, on this website, when you click on "Ask a question," the color remains on the tab.

Below is the code snippet I have been working on:

HTML

<ul id="parentExample" style="display: block;">
      <asp:Repeater runat="server" ID="uiMenuList">
        <ItemTemplate>
          <li id="childExample">
            <a id="uiMenuText" href="http://www.google.com" target="_blank" runat="server">First Menu</a>
            <a id="uiMenuText" href="http://www.google.com" target="_blank" runat="server">Second Menu</a>
            <a id="uiMenuText" href="http://www.google.com" target="_blank" runat="server">Third Menu</a>
          </li>
        </ItemTemplate>
      </asp:Repeater>
    </ul>
    

JavaScript

$(document.ready(function() {
      var $h3s = $('li').click(function() {
        $h3s.removeClass('active');
        $(this).addClass('active');
      });
    }));
    

CSS

.active {
      background: none;
      color: #FFC000;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }

    #parentExample li#childExample a {
      background: none;
      color: black;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }

    #parentExample li#childExample a:hover {
      background: none;
      color: red;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }

    #parentExample li#childExample a:active {
      background: none;
      color: #FFC000;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }

    #parentExample li#childExample a:selected {
      background: none;
      color: #FFC000;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }
    

Check out the code sample in action: JS Fiddle

Any assistance would be greatly appreciated

Thank you

Answer №1

Here is a different approach to consider:

$(document).ready(function() {
   $('li a').click(function() {
    $('li a').removeClass('active');
    $(this).addClass('active');
  });
});

Rearrange your CSS classes like this:

For example:

#parentExample li#childExample a {
  background: none;
  color: black;
  border: 0px;
  margin-top: -3px;
  margin-right: auto;
  margin-left: auto;
}

#parentExample li#childExample a:hover {
  background: none;
  color: red;
  border: 0px;
  margin-top: -3px;
  margin-right: auto;
  margin-left: auto;
}

#parentExample li#childExample a:active {
  background: none;
  color: #FFC000;
  border: 0px;
  margin-top: -3px;
  margin-right: auto;
  margin-left: auto;
}

#parentExample li#childExample a:selected {
  background: none;
  color: #FFC000;
  border: 0px;
  margin-top: -3px;
  margin-right: auto;
  margin-left: auto;
}

#parentExample li#childExample a.active {
      background: none;
      color: #FFC000;
      border: 0px;
      margin-top: -3px;
      margin-right: auto;
      margin-left: auto;
    }

You can view an example here: https://jsfiddle.net/mzwwrsca/3/

Answer №2

It is important to use !important when overriding CSS with a class instead of an id. This is because the id has higher specificity than a class.

.active {
  background: none !important;
  color: #FFC000 !important;
  border: 0px !important;
  margin-top: -3px !important;
  margin-right: auto !important;
  margin-left: auto !important;
}

Additionally, avoid using the $h3 variable in click events and remember to add and remove classes from anchor tags.

If you need to use a variable, do it like this:

var h3s = $('li a');
   $('li a').click(function() {
    h3s.removeClass('active');
    $(this).addClass('active');
  });

Make sure to include JQuery plugins and check out the Working Fiddle.

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

Angular - Async function does not resolve a rejected promise

Currently, my component utilizes an async method for handling file uploads. Here is an example: //component uploadPhotos = async (event: Event) => { const upload = await this.uploadService.uploadPhotos(event, this.files, this.urls); } The UploadSe ...

Stop future date selection in HTML using Vue

Looking for a way to ensure only past dates are selected in an HTML template. The chosen date is then sent to Vue for further processing. Check out the code snippet below. <div class="container text-center justify-content-center container-user&q ...

Exploring ways to modify the default Keep Alive behavior in Express JS

While stress testing a nodejs express server, I discovered that it automatically includes a "Connection: Keep-Alive" header. However, my application only needs to expose a web api to the client and does not require the connection to remain open after recei ...

Retrieving a data value using a specific key within a JavaScript object

Trying to retrieve a specific value by providing the literal key in a JavaScript object. The image below indicates that "filter" is equal to "Approved", sourced from reimb_status_description. Line 6 of code assigns filter to the value. const filter = Obj ...

Using Leaflet to make geojson XMLHttpRequests

Recently, I've been exploring the world of JavaScript and attempting to map around 2,200 data points in Leaflet. Despite following a helpful tutorial on pulling data from a geojson file and displaying it on a map, I can't seem to make it work wit ...

Having trouble with the "\" not working? Is there a way to use just one backslash instead?

I'm struggling with a little issue in Typescript - how can I use just one backslash? What I'm aiming for is an url pattern like this: "\/hello\/"+ urlRoute + "\/([0-9]*)", But when I attempt it, I end up with "/hello/"+ urlRoute ...

Allow AngularJS to make HTTP POST requests with CORS enabled

I am looking to submit a form to send an HTTP POST request to a server located on a different domain, with CORS enabled in the server script using Node.js. Below is the Angular configuration script: var myApp = angular.module('myApp', ['ng ...

What is the best way to incorporate a new item into Redux with a nested data structure similar to this? Specifically, I am looking to add new

Seeking assistance with dynamically pushing new items to a deeply nested choice array in order to render react native TextInput components using the map function. Below, you will find details on the data structure, reducer design, and other relevant code s ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

Tips for creating an indent in a new line

https://i.stack.imgur.com/O8Xbv.png I've been trying to figure out how to make the text indent on each new line when it's pushed to a new line due to screen resizing. I've tried using 'display:block' but it doesn't seem to wo ...

Circular graphs displaying percentages at their center, illustrating the distribution of checked checkboxes across various categories

Looking for a JavaScript script that displays results in the form of circles with percentage values at their centers, based on the number of checkboxes checked in different categories. The circle radius should be determined by the percentage values - for e ...

Transforming JavaScript to TypeScript in Angular: encountering error TS2683 stating that 'this' is implicitly of type 'any' due to lacking type annotation

While in the process of migrating my website to Angular, I encountered an error when attempting to compile the JS into TS for my navbar. After searching around, I found similar issues reported by other users, but their situations were not quite the same. ...

Scene lighting is now impacted by changes to the environment map in the latest r131 update

In my latest project, I am showcasing various models in a general scene. These models are created with different materials such as MeshPhongMaterial, MeshStandardMaterial, or sometimes both. The scene is illuminated by an AmbientLight and a DirectionalLig ...

Handling Pop-up Windows in Python with Selenium

# Automation Setup from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchAttributeException, NoAlertPresentException from selenium.webdriver.support.ui import WebDriverWait from seleniu ...

The nuSelectable plugin enhances the functionality of jQuery

I am currently experimenting with the jQuery nuSelectable plugin in order to enable users to select multiple items simultaneously. Unfortunately, I am encountering difficulties in making the selection work as intended. You can find the plugin here. After ...

Bug with the button and text input feature in Firefox

I am facing a strange issue where the button and input have the same CSS (except for the background), but Firefox is displaying them differently. This problem does not occur in IE or Chrome. #searchInput { width: 80%; margin: 0 auto; display: ...

Verifying Content in JavaScript

Here is a snippet of code I used to validate a Registration form on a content page. However, the validation part seems to not be functioning properly. Any assistance would be greatly appreciated. Master Page <%@ Master Language="C#" AutoEventWireup="t ...

Having trouble with printing the $length variable? Attempting to input data from duplicated forms

I have unique code presented below. In my HTML input tags, I have declared arrays named field, title[], first_name[], last_name[], email_address[], twitter_handle[]. These arrays were declared for form cloning purposes handled in a .js file. Now, my goal i ...

Updating materials within the Forge

Currently, we have implemented a system where the client retrieves object states when the page loads, changing the colors of 'pending' objects in the model. We continue to poll for changes to update the coloring - initially coloring pending objec ...

Refreshing chord chart information from a JSON source in d3.js

I have two functions that are responsible for creating and drawing a D3 chord diagram representing the netflow between different IP addresses in our network. Function 1 (for creating the chord diagram) function createChords(jsonURL, containerID, tooltipI ...