Pete Pete - 3 days ago 5
HTML Question

Changing color of text on click HTML

I'm currently learning HTML. I have to do an exercice where a text must change back and forth from red to green.
The code I have is below but doesn't seem to work. Any help would be appreciated.

.red { color : #FF0000 }
.green {color : #00FF00; }
<script type='text/javascript'>
function f(){
value=1
if (value == 1) {
document.getElementById("txt").className = "green";
value = 0
}
else if (value == 0) {
document.getElementById("txt").className="red"
value = 1
}
}
</script>
<p id='i1'>This is <em> special </em> <span id="txt" class='red'>text</span>.</p>
<p id="click" onclick='f();'>Click to change the colour of text</p>

Answer

Don't set any value. Check directly txt class.

function f(){
  var txt = document.getElementById("txt");

  if (txt.className == 'green') {
   txt.className = "red";
  }
  else {
    txt.className = "green";
  }
}

https://jsfiddle.net/fNPvf/33526/

Comments