Search code examples
javascripthtmljquerycssvisited

HTML CSS - Make icon change color when clicked (like a link)


When you click a link, typically it changes to purple, so you know that you've clicked that link. Usually resetting once you refresh or leave the page. Is there a way to make an icon (SVG or ) act like a link when clicked? And not just the last one clicked. It would be every single icon that gets clicked. I was trying to use the :visited pseudo, but it wasn't working.

.visit {
  fill: lightblue;
}

.visit:visited {
  fill: green;
}
<a href="#"><svg>
   <rect width='300' height='100' class='visit'></rect>
</svg></a>

jQuery and JavaScript answers are fine, but if there's a way to do this with just HTML and CSS, that would be preferred.


Solution

  • :visited is a link-related pseudo-class. It must be applied to the <a> tag.

    .visit {
      fill: lightblue;
    }
    
    a:visited .visit { /* Fix here */
      fill: green;
    }
    <a href="#"><svg>
       <rect width='300' height='100' class='visit'></rect>
    </svg></a>