Search code examples
javascriptcssspringif-statementthymeleaf

Css style change depending of value text


I would like to color the text in the with 4 different colors depending on the value. The value scale ranges from 0.0 to 10.0

For example: 0.0 to 2.5 red, 2.6 to 5.0 yellow, 5.1 to 7.5 blue, 7.6 to 10.0 green.

How can I do using javascript?

Be careful that the value within the is picked up by a Controller.

<span th:text="${value}">1.0</span>

If I wanted to use th: classappend?


Solution

  • you can do something like this in Pure Javascript:

    document.getElementById("btn").onclick = foofunc;
    
    
    function foofunc(){
    	var number = document.getElementById("test").value;
    	var div = document.getElementById("foo");
      div.style.fontSize = "50px";
      if (number >= 1 && number <= 2.5){
      	div.style.color = "Red";
      }
      else if (number >= 2.6 && number <= 5.0){
      	div.style.color = "Yellow";
      }
      else if (number >= 5.1 && number <= 7.5){
      	div.style.color = "Blue";
      }
      else if (number >= 7.6 && number <= 10){
      	div.style.color = "Green";
      }
      else{
      	div.style.color = "White";
      }
    }
    body {
        background-color: lightblue;
    }
    <input type = "number" id = "test">
    <button id = "btn">
    change
    </button>
    <div id = "foo" >1.0</div>

    Insert value in inputbox, click change, and it will change color according to your conditions.