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

Time:10-09

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>

CodePudding user response:

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>

CodePudding user response:

The default browser will use RGB when you refer to object.style.color, so the return value will not be "#000000", here is an example:

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>

CodePudding user response:

It is tricky testing style elements. In your case the color is RGB.

Instead toggle classes and test they are toggled

const cc = document.getElementById('font');
const btn = document.getElementById('btn2');
btn.addEventListener("click", e =>  {
  btn.classList.toggle("red");
  cc.classList.toggle("red");
  btn.textContent = btn.classList.contains("red") ? "Red" : "Black";
})
.red { color: red; }
#font {font-size: 25px;}
<p id="font" >Lorem Ipsum</p>

 <button type="button" id="btn2" >Red</button>

  • Related