css - Javascript If/else style changing -


i have problem simple if else statement changes text color of <p> element depending on current color. see why results can't seem find solution. newbie me appreciated.

html

<p id="demo">javascript can change style of html element.</p> 

js try 1

<script>  var x = document.getelementbyid("demo");      function one() {    x.style.fontsize="16px"; x.style.color="black";}  function two() {  x.style.fontsize="16px"; x.style.color="red";}  function three(){  if(x.style.color="black") { two() } else {one() } } </script>` <button type="button" onclick="three()">click me!</button> 

js try 2

<script>  var brojilo = 1 ; function three(){   var x = document.getelementbyid("demo");  function two() {  x.style.fontsize="18px"; x.style.color="red";}  function one() {    x.style.fontsize="18px"; x.style.color="black";}  if (brojilo % 2 == 0) {one()}  else {two()}  var brojilo = brojilo + 1 ;  } </script><button type="button" onclick="three()">click me!</button> 

js try 3

<script>  var b2 = 0 ;  function brojanje(){ var b2 = b2+1;}  function three(){   var x = document.getelementbyid("demo");  function two() {  x.style.fontsize="18px"; x.style.color="red";}  vfunction one() {    x.style.fontsize="18px"; x.style.color="black";}  if (b2 % 2 == 0) {one()}  else {two()} } </script><button type="button" onclick="three(); brojanje ();">click me!</button> 

you can use getcomputedstyle element's color.

window.getcomputedstyle(x, null).color

since value of color property of 'demo' element hasn't been initialized, contains default value of rgb(0, 0, 0) corresponds color black.

see below example of toggling between 2 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 style of html element.  </p>  <input type="button" onclick="togglecolor()" value="toggle color">


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -