Search code examples
javascripthtmlcss

How to change color based on number


I have just started to learn coding and I have got a problem now. I have made this black circle witch has number inside and it goes higher every time you click it but I would want now that even numbers would be blue and odd numbers red (1=red, 2=blue, 3=red etc.)

window.onload = function(){
    var laskuri = document.getElementById('laskuri'); 
    function kasvata() {
        var i =++
        laskuri.innerHTML + i;

        asetaTaustaVari();
    }

    function asetaTaustaVari() {

    }

    laskuri.onclick = kasvata;

}
* {
        box-sizing: border-box;
    }

    main {
        text-align: center;
    }

    #laskuri {
        width: 300px;
        height: 300px;
        background-color: black;
        color: white;
        margin: 50px auto;
        font-size: 200px;
        padding: 30px 0px;
        border-radius: 50%;
        cursor: pointer;
    }
<div id=laskuri>0</div>
    


Solution

  • You can simply do it by putting an if condition and setting color in it

     if (val % 2 == 0) {
          color = "blue";
        } else {
          color = "red";
        }
    

    or use ternary operator like this

    function kasvata() {
      var color = '';
      var i = ++
      document.getElementById('laskuri').innerHTML + i;
      var el = document.getElementById('laskuri');
      color = el.innerHTML % 2 == 0 ? "blue" : "red";
      el.style.color = color;
      asetaTaustaVari();
    }
    
    function asetaTaustaVari() {
    
    }
    
    laskuri.onclick = kasvata;
    <html lang="fi">
    
    <head>
      <meta charset="utf-8">
      <title>Laskuri</title>
      <style>
        * {
          box-sizing: border-box;
        }
        
        main {
          text-align: center;
        }
        
        #laskuri {
          width: 300px;
          height: 300px;
          background-color: black;
          color: white;
          margin: 50px auto;
          font-size: 200px;
          padding: 30px 0px;
          border-radius: 50%;
          cursor: pointer;
        }
      </style>
    </head>
    
    <body>
      <main>
        <div id=laskuri>0</div>
    
      </main>
    </body>
    
    </html>