I’m a front-end beginner and want to create a project with javascript that makes a relationship between environmental parameters, like temperature, pressure, or everything with color; as those parameters change, the color changes. So I tried a simple project and create two buttons for getting the temperature up and down and a colored div to show the temperature change. As the temperature gets higher the color of the div goes to the red spectrum and as it gets lower, the color of the div goes to the blue spectrum like a color mixer in the w3schools site here and I used hex color values.
The problem is when I use hex values for color, the code doesn’t work but when I tried integer values for example for changing the height of the div when the buttons push and the value of the height gets up and down, it worked. so it has a problem with hex color values.
By the way, I searched for the same javascript projects like color slider, color gauge, or something and also searched the questions that were related to color changing in the stack, but was not helpful.
<html>
<head>
<style>
#cool{
background-color:lightblue;
float:left;
}
#hot{
background-color:red;
float:right;
}
button{
width:200px;
height:100px;
font-size:20pt;
}
#range{
width:100%;
height:50px;
background-color:#ff0000;
}
</style>
</head>
<body>
<div id="range"> </div>
<button id="hot" type="button" onclick="tempUp()"> hot </button>
<button id="cool" type="button" onclick="tempDown()"> cool </button>
</body>
<script>
var colorVal = [ff0000,b2004c,5900a6,0000ff]; //from red to blue
var i = 0; //default value
function tempUp(){
if(i < 3){
i++;
document.getElementById('range').style.backgroundColor = colorVal[i];
}
}
function tempDown(){
if(i > 0){
i--;
document.getElementById('range').style.backgroundColor = colorVal[i];
}
}
</script>
</html>
I tried converting hex color values to decimal but that didn’t work.
3
Answers
You’re really close! Just a couple of things:
colorVal
array:colorVal
array is in the wrong order: As you increment withtempUp()
, the index increases, but the colors are going from red –> blue – which is the opposite of what you want.#
This is a possible solution:
This goes from blue –> red.
i
value starts at index0
, but should be at index3
because the array order is now reversed. If you want, you can revert the array order from red –> blue, and keep the starting index at0
.Here’s a working snippet:
For this kind of use, the hexadecimal format is not the most suitable.
You better use HSL, the color will be defined by the hue between 0 and 360° as below:
For example, for a gauge from blue to red, you can move the hue from 225 to 0°
If you want to use hex values, try this (although using directly decimal values doesn’t need base conversion):