I am trying to make this script more concise, since I will be adding on more statements in the future.
x = Math.floor((Math.random() * 9) + 1);
var one = document.getElementById("test");
if(x === 1) {
one.style.backgroundColor = "red";
}
if(x === 2) {
one.style.backgroundColor = "blue";
}
if(x === 3) {
one.style.backgroundColor = "yellow";
}
You can store the properties and values in a plain object
const o = {1:'a',2:'b',3:'c'}
one.style.backgroundColor = o[x]
If you do not need the random value for other purpose, you could take an array and check if you got a truthy value for setting the color.
var x = ['red', 'blue', 'yellow'][Math.floor(Math.random() * 9)],
one = document.getElementById("test");
if (x) one.style.backgroundColor = x;
<div id="test">test</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With