Murtuza Z
Murtuza Z

Reputation: 6017

Change colors of <a> tags using java script

I am very new to UI world. I am facing problem in static html page.

( Please note we are not using any JS framework in my project, Please help me with pure java script code)

Now here what i want to archive is, when i click on YAHOO, it should become orange colored and Google & Bing white when i click on GOOGLE, it should become orange colored and Yahoo & bing white when i click on BING, it should become orange colored and Yahoo & Google white

1) In my html page i have multiple links ,like below

<a href="www.yahoo.com">Yahoo</a>
<a href="www.google.com">Google</a> 
<a href="www.bing.com">Bing</a>

2) I have one CSS file which contains below,

a {text-decoration: none}
a:link, a:visited {text-decoration: none;color: white;}
a:hover {text-decoration: none; color: #FF9900;}

Upvotes: 0

Views: 114

Answers (1)

reuelab
reuelab

Reputation: 1986

EDIT: Edited function // Using PURE JS // UPDATED FIDDLE

add idand onclick attributes to each link like:

<a href="#" id="googleLink" onclick="changeColor(this)">Google</a><br />
<a href="#" id="yahooLink" onclick="changeColor(this)">Yahoo</a><br />
<a href="#" id="bingLink" onclick="changeColor(this)">Bing</a>

change the color using a javascript function:

function changeColor(link) {
document.getElementById(link).className = "activeLink";
if(link == "googleLink"){
  document.getElementById("yahooLink").className = "";
  document.getElementById("bingLink").className = "";
   }
if(link == "yahooLink"){
  document.getElementById("googleLink").className = "";
  document.getElementById("bingLink").className = "";
   }
if(link == "bingLink"){
  document.getElementById("googleLink").className = "";
  document.getElementById("yahooLink").className = "";
   }
}

and style it using this css:

.activeLink{
    color: orange;
}
.activeLink:hover{
    color: orange; // *so the active link would not change color on mouse hover
}

Upvotes: 2

Related Questions