Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Div class depending on value with small increments

I'm trying to create a Div that can have about 100 different shades depending on the value of a variable which in this case is "votes". The more upvotes the redder the button. The more downvotes the bluer the button.

I can easily make a function like this with 8 classes :

$scope.divColor = function (votes) {
    if (votes < 60)
        return "blue60";
    else if (votes >= 60 && votes <= 69)
        return "blue70";
    else if (votes >= 70 && votes <= 79)
        return "blue80";
    else if (votes >= 80 && votes <= 89)
        return "blue90";
    else if (votes >= 90 && votes <= 99)
        return "red100";
    else if (votes >= 100 && votes <= 109)
        return "red110";
    else if (votes >= 110 && votes <= 119)
        return "red120";
    else if (votes >= 120)
        return "red130";
}

But is there anyway to have a variable somewhere that uses the votes value to set the actual background-color rather than the class?

like image 474
ChrisM Avatar asked Dec 14 '22 08:12

ChrisM


1 Answers

Set a 1000% gradient background from red to blue then when the vote is updated, simply change its position on javascript: document.getElementById("element").style.backgroundPosition = "0% 50%";. Where min(red): 0% 0% middle(purple): 0% 50% max(blue): 0% 100%

UPDATE: As you see below on the comments, use "100000%" instead of "1000%" to avoid any gradient shade of being noticed.

function test(){

var votes = document.getElementById("test").value;  
document.getElementById("testobj").style.backgroundPosition = "0% " + votes + "%";
  
}
.square {
  width:100px;
  height:100px;
  background: linear-gradient(0deg, skyblue, tomato);
  background-size: 100000% 100000%;
  float:left;
  line-height: 100px;
  text-align: center;
  outline: 2px solid black;
}

input {
  margin-left: 5px;
  width: 100px;
  display: inline-block;
  vertical-align: middle;
}

.A {
  background-position:0% 0%;  
}

.B {
  background-position:0% 50%;  
}

.C {
  background-position:0% 100%;
}

.D {
  width:100px;
  height:100px;
  background: linear-gradient(0deg, skyblue, tomato);
  background-size: 100000% 100000%;
  display: inline-block;
  line-height: 100px;
  text-align: center;
  outline: 2px solid black;
}
<div class="square A">0%</div>
<div class="square B">50%</div>
<div class="square C">100%</div>
<input id=test type="range" name="votes" min="0" max="100" oninput="test()">
<div id=testobj class="D">Slider test</div>
like image 175
Le____ Avatar answered Dec 17 '22 01:12

Le____