javascripthtmlcssgetcomputedstyle

Computed Style not working with overwritten CSS variables


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 --visitedBSA to true.

The problem is, in my JavaScript, using getComputedStyle(document.getElementById("link1")).getPropertyValue("--visitedBSA") 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 {
  --visitLink1: 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>


Solution

  • Just check if the color of the link is purple using the getComputedStyle(). Or add a click event listener on each link like this-

    link.addEventListener("click", e => {
       e.preventDefault();
       link.style.setProperty("--visitedLink1", "true")
       window.open(link.href, "_blank")
    })
    

    Info- You were assigning --visitedBSA to true in a:visited but searching for --visitedLink1 === "true" in js

    Edit- You still cannot access any CSS property declared in :visited using javascript getComputedStyle() so the best option would be to use the hacky solution prescribed at the beginning (overriding each link's click event)