Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I change the color of a text with a button in Java Script?

So like my previous question, I am once again asking for your JavaScript support.
This is what I’ve come up with which for some reason, doesn’t work:

function changecolor() {
    let cc = document.getElementById('font');
    let btn = document.getElementById('btn2');

    if (cc.style.color == '#000000') {
        cc.style.color = '#ff0000';
        btn.innerHTML = 'Black'; 
    }
    else if (cc.style.color == '#ff0000') {
        cc.style.color = '#000000';
        btn.innerHTML = 'Red';
    }

}
<p id="font" style="font-size: 25px; color: #000000;">Lorem Ipsum</p>

 <button type="button" id="btn2" onclick="changecolor()">Red</button>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If you console.log the color (console.log(cc.style.color)), you would see (in Chrome at least), that the color is logged as an RGB value (rgb(0, 0, 0)).

So just change the conditions:

function changecolor() {
  let cc = document.getElementById('font');
  let btn = document.getElementById('btn2');

  console.log(cc.style.color)

  if (cc.style.color == 'rgb(0, 0, 0)') {
      cc.style.color = '#ff0000';
      btn.innerHTML = 'Black'; 
  }
  else if (cc.style.color == 'rgb(255, 0, 0)') {
      cc.style.color = '#000000';
      btn.innerHTML = 'Red';
  }
}
<p id="font" style="font-size: 25px; color: #000000;">Lorem Ipsum</p>

<button type="button" id="btn2" onclick="changecolor()">Red</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading