Is there a way to change the color of just the most recently clicked anchor element <a>?

I have a sidebar with anchor elements (Link 1,2,3 in my HTML). I want the text color of these anchors to change when clicked. Additionally, I need only one anchor element to be colored at a time, meaning the previous one should return to its normal color. How can I achieve this?

Below is the link to access my HTML code: https://pastebin.com/ew9qXAzH

The following shows the anchor elements in my code:

<div class="sidenav">
  <button class="dropdown-btn">Dropdown1 
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-container">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  <button class="dropdown-btn">Dropdown2 
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-container">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
</div>

Answer №1

It seems that the CSS pseudo-class :focus retains the color of the last clicked element until another element is clicked on within the page.

a:focus { color: green; }
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>

Answer №2

There are specific CSS selectors designed for this purpose.

a:link and     a:visited.

The first one applies when the link is in its normal state, while the second one applies when the link is clicked on, like so you can go like >

a:link {
  color: red;
}

a:visited {
  color: green;
}

Additionally, you can utilize a:active, which activates immediately upon clicking the link but reverts to its original color as soon as the click event ends (effect lasts around 0.01 seconds).

Answer №3

To make all the links stand out, I assigned them a class called "highlightLink" and added an onclick event handler "linkSelected()". Here is a snippet of the JavaScript code:

function linkSelected() {
    var links = document.querySelectorAll(".highlightLink"); // get all the links
    links.forEach(link => link.style.fontWeight = "normal"); // set font weight of all links to default (normal)
    event.target.style.fontWeight = "bold"; // set font weight of the clicked link to bold (or any style you prefer)
}

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

Using Vuex and array.findIndex but unable to locate a matching element

I am encountering an issue with the array.findIndex method. Despite being certain that there is a match in the array I am searching through, findIndex consistently returns -1. let index = state.bag.findIndex((it) => { it.id === item.id console. ...

Each time forEach is called, it increments the previous result by 1

My service returns a response containing the following data: {"id":157336,"results":[ {"id":"53db3c790e0a26189a000d09","iso_639_1":"en","key":"ePbKGoIGAXY","name":"Trailer 3","site":"YouTube","size":1080,"type":"Trailer"}, {"id":"550df44b925141355 ...

Creating and fetching CSV files using PHP and AJAX

I have successfully created a PHP script that generates a CSV file for automatic download by the browser. The code below shows a working version with sample data for different car models. <?php $cars = array( array("Volvo",22,18), array("BMW",15,1 ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

Guide to creating a custom wrapper for a Material UI component with React JS

I am utilizing the Material UI next library for my project and currently working with the List component. Due to the beta version of the library, some parameter names are subject to change. To prevent any future issues, I have decided to create a wrapper a ...

What is the best way to remove an element from an array and add a new one?

Here is the array that I am working with: [ { "id": "z12", "val": "lu", "val2": "1", }, { "id": "z13", "val": "la", "val2" ...

Show various error messages depending on the type of error detected

When pulling data from an API, my goal is to handle errors appropriately by displaying custom error messages based on the type of error that occurs. If the response is not okay, I want to throw an error and show its message. However, if there is a network ...

Challenges with exporting dynamically generated divs using jspdf in an Angular 2 project

I have been utilizing the jspdf library to print div elements in my current project. But I recently discovered an issue where dynamic content within a div is not being printed correctly. Specifically, when incorporating simple Angular if statements, jspdf ...

Tips for managing open and closed components within a React accordion and ensuring only the clicked component is opened

Unique Accordion component: const CustomAccordion = (props: AccordionProps) => { const { label, levels, activeId, id } = props const [isExpand, setIsExpand] = useState(false) const onPress = useEvent(() => { setIsExpand( ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Adding a JavaScript widget to a WordPress page

Good morning! I need to place an affiliate external widget on a WordPress page. The code I have loads external content within the page. <script type="text/javascript" src="http://www.convert.co.uk/widget/mobiles.js"></script> The placement o ...

Enhance the functionality of a directive by incorporating the ui-mask directive

Recently, I implemented a custom directive for an input field that adds a calendar icon with a datepicker to the input. I have used this directive in various sections of my application and now I am interested in incorporating ui-mask - another directive I ...

Tips for transmitting an array of Objects to AngularJS

Summary I'm curious about how I can successfully send the following array of objects from NodeJS to an AngularJS app. var players = [ Footer: { username: 'Footer', hp: 200, exp: 1 }, Barter: { username: 'Barter', hp: 200, e ...

Using Jquery Chosen Plugin to Dynamically Populate One Chosen Selection Based on Another

Good evening to all, please excuse any errors in my English. I have successfully integrated a jQuery Chosen plugin with my 'estado' field (or province). My goal is to populate another jQuery Chosen plugin with the cities corresponding to that s ...

From AJAX response to React state attribute, store the JSON data

I have a component where I need to fetch freight values via ajax and store them in the state property of this class. import React, { Component } from 'react'; import Freight from './Freight'; import CreateFreightEntryModal from '. ...

The issue with Angular 4 imports not refreshing in a .less file persists

Currently, I am in the process of developing a small Angular project that utilizes less for styling purposes. My intention is to separate the styling into distinct folders apart from the components and instead have a main import file - main.less. This fil ...

extracting the ID from within an iframe

Currently, I am developing a script using pure javascript. parent.*nameofiframe*.document.getElementById('error').value; However, when attempting to achieve the same using jQuery, it doesn't seem to work: $('*nameofiframe*', win ...

Struggling to unlock the mystery of a jammed trigger box

I'm currently working on implementing a small 'trigger box' that will expand upon clicking. It was functional before, but it seems to be encountering an issue now and I'm unsure of the cause. While I have some understanding of HTML and ...

Tips for controlling the size of a canvas element: setting minimum and maximum width and height properties

function convertImageResolution(img) { var canvas = document.createElement("canvas"); if (img.width * img.height < 921600) { // Less than 480p canvas.width = 1920; canvas.height = 1080; } else if (img.width * img.he ...

Troubleshooting issues with AngularJS's minDate functionality

I have been trying to set the minDate for the datepicker to today, following the example on the angularJS bootstrap site. However, it seems like something is not working correctly. There are no console errors showing up, but it appears that the minDate is ...