Random Programmer
Random Programmer

Reputation: 23

How do I change the css of a link when visited, unvisited or hovered using javascript?

So in my html code I have a line of code that looks like what is shown in the bottom:

    <a href = "https://www.youtube.com/watch?v=dQw4w9WgXcQ">Find out more</a>

and I want to use java script to change the color of this link when visited, not visited or hovered. In other word, what I am looking for is a way to do what is shown below but with java script.

    a.visited {css property}; a.link {css property}; a.hover {css property}

Does anyone know how? Any help would be appreciated.

Upvotes: 0

Views: 924

Answers (1)

CherYang
CherYang

Reputation: 71

From your CSS, you can have a default style of your link as below and make use of the CSS variables

a{
    --color:lightblue;
    --hoverColor: red;
    --visitedColor: blue; 
    color: var(--color);
}

a:hover {color:var(--hoverColor);}
a:visited:hover {color:var(--hoverColor);}
a:visited {color:var(--visitedColor);}

From your JavaScript, you can override the hoverColor and visitedColor css variable as below

document.querySelectorAll("a").forEach(function(link){
    link.style.setProperty('--hoverColor','orange');
});

document.querySelectorAll("a").forEach(function(link){
    link.style.setProperty('--visitedColor','blue');
});

Upvotes: 1

Related Questions