Search code examples
javascripthtmlcsscolorstextcolor

javascript - Change text color multiple times between two color ranges


I was wondering if someone could help me change the color of the text multiple times then form color #627CA9 to #FFFFFF and vice versa.

I Tried this:

function changeColor(id) {
  var x = document.getElementById(id);
  if (document.getElementById(id).style.color = "#627CA9")
    document.getElementById(id).style.color = "#FFFFFF"
  else {
    document.getElementById(id).style.color = "#627CA9"; // forecolor
  }

}
<div style="cursor: pointer;" onclick="changeColor('myid1'); return false;" id="myid1" class="centered">CHVRCHES</div>
<div style="cursor: pointer;" onclick="changeColor('myid2'); return false;" id="myid2" class="centered">PVRIS</div>

The code only changes the color 1 time.

(Sorry my english)

Thanks


Solution

  • Aside from the fact that you're assigning the colour with "=" instead of checking it with "==", the colour is also being set as RGB. Checking against this seems to work;

    function changeColor(id) {
      var x = document.getElementById(id);
      
      if (x.style.color != "rgb(255, 255, 255)")
        x.style.color = "#FFFFFF";
      else {
        x.style.color = "#627CA9"; // forecolor
      }
    
    }
    <div style="cursor: pointer;" onclick="changeColor('myid1'); return false;" id="myid1" class="centered">CHVRCHES</div>
    <div style="cursor: pointer;" onclick="changeColor('myid2'); return false;" id="myid2" class="centered">PVRIS</div>