Skip to content Skip to sidebar Skip to footer

Change The Color Of Anchor When Clicked?

Noob here. I have these 3 buttons type anchors and I want to change their color when they are clicked. I'm almost there but the thing is when the color changes if you click elsewhe

Solution 1:

add this to ur css

.button:visited{
    background: blue;
}

all links clicked will change color

More info here link

.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px2px;
  cursor: pointer;
}

.button:active {
  background: red;
}

.button:focus {
  background: red;
}

.button:visited {
  background: blue;
}
<ahref="#/test3"class="button">Link 1</a><ahref="#/test2"class="button">Link 2</a><ahref="#/test"class="button">Link 3</a>

Solution 2:

I think you are looking for this: https://www.w3schools.com/howto/howto_js_active_element.asp

This will add active class to the button (you can simply change that to your a tags) you clicked on. Even after you will click elsewhere on the screen.

Hope it solved it, and good luck!

Solution 3:

Try this js code

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++) {
  links[i].onclick = function() {
    this.style.backgroundColor = "red";
  }
}
.button {
  background-color: #4CAF50;
  border: none;
  color: white;
  padding: 15px32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
  margin: 4px2px;
  cursor: pointer;
}

.button:active {
  background: red;
}

.button:focus {
  background: red;
}
<ahref="#"class="button">Link 1</a><ahref="#"class="button">Link 2</a><ahref="#"class="button">Link 3</a>

Post a Comment for "Change The Color Of Anchor When Clicked?"