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

1.7k Views Asked by At

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.

4

There are 4 best solutions below

1
acemir On BEST ANSWER

: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>

0
Talmacel Marian Silviu On

Like this and use a different number after # for every element you want to use this on.

.visit {
  fill: lightblue;
}

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

0
Mike Donkers On

If I understood your question correctly, you can use the active pseudo for this. This will make it so that when the link is active (i.e. clicked) turn green in this case.

For more information on the active pseudo, please see this site

a {
  padding: 10px;
}
  
.visit {
  fill: lightblue;
}

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

0
acyclone On

Here is a working sample!

.box {
  width:  300px;
  height: 300px;
}

.box * {
  width: 100%;
  height: 100%;
}

.box .visit {
  fill: #ccc;
}

.box:link .visit {
  fill: #999;
}

.box:hover .visit {
  fill: #3f9;
}

.box:active .visit {
  fill: #f93;
}

.box:visited .visit {
  background: #39f;
}
<a href="#" class='box'>
  <svg>
    <rect class='visit'>
    </rect>
  </svg>
</a>