Adjusting the color of text using Javascript while keeping the hover color untouched

The following CSS is applied:

.overlay-left-a {
  color: red;
}
.overlay-left-a:hover {
  color: black;
}

Additionally, this JavaScript code is included:

let gr1 = document.getElementsByClassName("overlay-left-a");
for (let i = 0; i < gr1.length; i++) {
  gr1[i].style.color = blue;
}

However, I want to ensure that the JavaScript does not change the ':hover' color. Can you provide me with the best approach for achieving this?

Answer №1

If you're looking to update a CSS variable without affecting the hover color, you can achieve it like this:

:root {
    --color: red;
}
.overlay-left-a {
    color: var(--color);
}

To change the value of the color on :root, you can use the following JavaScript code:

document.documentElement.style.setProperty("--color", "blue");
//                                    Or any other color value −−−−^^^^^^

Check out the live example below:

document.querySelector("input[type=button]").addEventListener("click", (e) => {
    // Get the new color from input
    const color = document.getElementById("txt-color").value.trim();
    
    // Apply the new color
    document.documentElement.style.setProperty("--color", color);
});
:root {
    --color: red;
}

.overlay-left-a {
    color: var(--color);
}

.overlay-left-a:hover {
    color: black;
}
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<a href="" class="overlay-left-a">test</a>
<div>
    <label>
        Color name: <input type="text" id="txt-color" value="blue">
    </label>
    <input type="button" value="Set Color">
</div>

Answer №2

Try using a different class instead of inline styles, utilizing :not(:hover) to exclude applying the style to elements being hovered over. (You can nest a simple selector inside the negation-pseudo class.

.overlay-left-a.blue:not(:hover) {
  color: blue;
}

document.querySelector("input[type=button]").addEventListener("click", (e) => {
    e.currentTarget.disabled = true;
    let gr1 = document.getElementsByClassName("overlay-left-a");
    for (let i = 0; i < gr1.length; i++) {
        gr1[i].classList.add("blue");
    }
});
.overlay-left-a {
  color:red;
}
.overlay-left-a:hover {
  color:black;
}
.overlay-left-a.blue:not(:hover) {
  color: blue;
}
<div class="overlay-left-a">hover me</div>
<input type="button" value="Click To Change Color To Blue">


You mentioned that the color is dynamically provided in a comment, so the aforementioned approach may not suit your specific needs.

To handle this, you can utilize a CSS variable as demonstrated by mmh4all. If using a CSS variable is not an option due to outdated browsers or other reasons, you can add a style element to your page:

document.querySelector("input[type=button]").addEventListener("click", (e) => {
    // Get the color
    const color = document.getElementById("txt-color").value.trim();

    // Create or update a style element applying that color
    // to `.overlay-left-a` elements
    let style = document.getElementById("overlay-left-a-color");
    if (!style) {
        style = document.createElement("style");
        style.id = "overlay-left-a-color";
        document.querySelector("head").appendChild(style);
    }
    style.textContent = `.overlay-left-a:not(:hover) { color: ${color}; }`;
});
.overlay-left-a {
  color:red;
}
.overlay-left-a:hover {
  color:black;
}
<div class="overlay-left-a">hover me</div>
<label>
    Color name: <input type="text" id="txt-color" value="blue">
</label>
<input type="button" value="Set Color">

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

Is there a way to enable access to the BTable properties beyond the table itself?

I am in need of a way to close the details of one row from another row. My current strategy involves using the index number of each row to check the value of showdetails. However, I have not been successful in accessing one row object from within another. ...

Error: Webpack encountering reference errors when handling multiple entry points

Here is my setup in webpack.config.js: entry: { a:'./src/a.js', b:'./src/b.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name].bundle.js' } The content of a.js includes: const ...

Display the variable value in an HTML format following the submission of a request to an API using NODE JS, express, and jquery

Seeking assistance with completing a straightforward task: Creating an HTML AJAX link that triggers a Node.js API call to retrieve a value, wait for the response, and then display the value in HTML, JS, or PHP. After clicking on the "Get My Value" link be ...

What could be causing my Bootstrap 4.0 beta to malfunction?

I recently downloaded Bootstrap 4.0 beta from getbootstrap.com and included the CSS & js files from the dist folder. However, I noticed that some styles such as navbar, hidden, and visible are not working properly. Do I need to include any additional fil ...

How to change the color of the tooltip text in Bootstrap Vue

In an attempt to modify the color of the tooltip text from its default to red https://i.sstatic.net/fF78X.png Any payment made during the night hours (00:00 – 06:00) must be displayed as red. ...

Is the Webpack vendors JS bundle in Vue CLI containing unlisted code that is not in the dependencies or package-lock.json file?

An information security auditing tool flagged an outdated library with known vulnerabilities in our webpack-bundled chunk-vendors.js file generated using Vue CLI: The library in question is YUI 2.9.0. It appears that this library is not fully included, a ...

What caused the failure of the ++ operator in production mode?

Encountering an issue with a reducer in my code. There is a button with an onClick function that triggers a NextBox action to alter the state of a React UseContext. The application was built using Vite, and while running npm run dev, everything functions a ...

Increase the value within a singular document and transfer written text to a separate file

I have an HTML script that includes a form. This form sends a Name value to a PHP script. In the PHP script, I read two different text files - one to retrieve a number and increment it by 1, and the other to write the incremented number along with the Name ...

Displaying random characters in place of Angular 6 font awesome icons

Recently, I started a new project with the angular cli and incorporated font-awesome 4.7.0. After that, I included it as a dependency in my angular.json file. "styles": [ "./node_modules/font-awesome/css/font-awesome.min.css", "./node ...

Is it possible to use powershell to simulate clicking on an angularjs button?

<div class="w-btn" ng-click="vm.callbacks.compareAll();" ng-if="vm.folderData.projects.length > 0 &amp;&amp; vm.noneSelectedProjects" tabindex="0"><i class="glyphicon glyphicon-transfer btn-icon"></i> Report from all</div> ...

The Facebook comment section is taking control

<div class="fb-comments" data-href="https://www.facebook.com/pages/Societ%C3%A0-Ginnastica-Triestina-Nautica/149520068540338" data-width="270" data-num-posts="3"> I'm having trouble with the comment box extending past my div height and overlapp ...

Finding descendants using a jQuery object that has been saved

As I cycle through some unordered lists, I aim to retrieve all of the descendants using the saved jquery-wrapped selectors. Below is the HTML snippet: <ul> <li><a href="#">item 1</a></li> <li><a href="#"> ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

How to apply styles to a child component using CSS modules in a parent component

For the styling of a Material UI component (Paper) within a Menu component, I am referencing this documentation. To style my components using CSS modules with Webpack as the bundler, here's an example: // menu.js import React from 'react'; ...

Best practices for referencing attributes created with the data method in a Vue component

In my application, there is a section that displays a list of users along with a search box to filter names. The user information is fetched from a database and stored in app.users. I have created a component named 'user' to show the details of e ...

Error: The "checkAvailability" method is not available in the model object

When attempting to implement some functionality methods for my model, I encountered an issue where sending a request resulted in the following traceback: /home/nano/Dev/JS/OMI/node_modules/mongoose/lib/utils.js:413 throw err; ^ TypeE ...

JavaScript: Reorder an array to alternate between largest and smallest elements, starting with the largest

When working with an array of integers that need to be sorted in a specific order, such as: [1, -1, -3, 9, -2, -5, 4, 8,] We must rearrange them so that the largest number is followed by the smallest number, then the second largest number followed by the ...

Pass data from Action Class to ajax using JSON syntax

Currently I am facing an issue while working on fullCalendar, a jQuery plugin. I am trying to populate event details from a database when the Calendar page loads, but I seem to be stuck with a silly problem that I can't figure out. $('#calendar& ...

Modifying the appearance of PHP code by applying CSS styles to the font

Here is the HTML code: <!DOCTYPE html> <html> <head> <title>Greeting Service!</title> <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css' /& ...

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...