I’m making a website search engine like Google, and when a thing is visited I want to it turn green and change a tooltip. I use :visited
to do that, and the code changes it to purple and sets a variable --visitedLink1
to true.
The problem is, in my JavaScript, using getComputedStyle(document.getElementById("link1")).getPropertyValue("--visitedLink1")
gives the :root value, not the updated value after visiting the website. Thus, when updating the tooltip, its "not visited" and sets the tooltip to "not visited" instead of "visited"
var mousePos = {
x: undefined,
y: undefined
};
window.addEventListener('mousemove', (event) => {
mousePos = {
x: event.clientX,
y: event.clientY
};
document.getElementById("tt").style.left = mousePos.x + 10;
document.getElementById("tt").style.top = mousePos.y + 10;
var cs = getComputedStyle(document.getElementById("link1"))
console.log(cs.getPropertyValue('--visitedLink1'))
if (cs.getPropertyValue('--visitedLink1') == "true") {
document.getElementById("tt").innerHTML = "Visited"
}
});
:root {
--visitBSA: false;
}
a {
color: blue;
}
#link1:visited {
--visitBSA: true;
color: purple;
}
.tooltip {
position: absolute;
display: none;
background-color: wheat;
border-radius: 10px;
padding: 20px;
border: 3px solid black;
left: 0;
top: 0;
}
a:hover~.tooltip {
display: block;
}
<h1>Search</h1>
<div class="text">Link 1: <a id="link1" href="https://www.scouting.org">scouting.com</a>
<div id="tt" class="tooltip">Not visited</div> troop.</div>
2
Answers
Just check if the color of the link is purple using the getComputedStyle(). Or add a click event listener on each link like this-
Info- You were assigning
--visitedBSA
to true ina:visited
but searching for--visitedLink1 === "true"
in jsYou cannot access
:visited
styles from JavaScript, for security/privacy reasons.In addition, it appears that CSS custom properties ("CSS vars") cannot be set in
:visited
styles. I suppose because of the complexity of keeping track of where they are used and preventing access.This snippet shows that you cannot access changed styles:
And this one shows that CSS custom properties are not settable: