Martin Markovic
Martin Markovic

Reputation: 129

JavaScript If / Else style changing

I have a problem with simple if/else statement that changes text color of a <p> element depending on the current color. I see why I get certain results but I can't seem to find a solution.

var test = 1;

function one() {  
    x.style.fontSize = "18px";
    x.style.color    = "black";
}

function two() {
    x.style.fontSize = "18px";
    x.style.color    = "red";
}

function three() { 
    var x = document.getElementById("demo");
    if (test % 2 == 0) {
        one();
    } else {
        two();
    }
    test = test + 1;
}
<p id="demo">JavaScript can change the style of an HTML element.</p>
<button type="button" onclick="three()">Click Me!</button>

Any help for a newbie like me would be appreciated.

Upvotes: 0

Views: 14343

Answers (3)

zuoyan.wu
zuoyan.wu

Reputation: 71

u can use a variable to cache current color, for example:

(function(){
  var color = 'red';

  var demoEl = document.getElementById("demo");
  demoEl.addEventListener('click', function(e) {
      if (color === 'red') {
          demoEl.style.color = 'black';
          color = 'black';    // set current color
      } else {
          demoEl.style.color = 'red';
          color = 'red';
      }
  }, false);
})();

<p id="demo">JavaScript can change the style of an HTML element.</p>

Upvotes: 1

Ricardo Rossi
Ricardo Rossi

Reputation: 524

You can use getComputedStyle to get the element's color.

window.getComputedStyle(x, null).color

Since the value of the color property of your 'demo' element hasn't been initialized, it contains the default value of rgb(0, 0, 0) which corresponds to the color black.

See below for an example of toggling between two colors:

var black = 'rgb(0, 0, 0)';
var red = 'rgb(255, 0, 0)';

function toggleColor() {
  var x = document.getElementById("demo");
  var currentColor = window.getComputedStyle(x, null).color;

  if(currentColor === black) {
    x.style.color = red;
  } else {
    x.style.color = black;
  } 
}
<p id="demo">
  JavaScript can change the style of an HTML element.
</p>
<input type="button" onclick="toggleColor()" value="Toggle Color">

Upvotes: 2

Script47
Script47

Reputation: 14540

Use getComputedStyle, style is used for inline CSS.

Upvotes: 0

Related Questions