I’m building my first JS project and I want to generat a number from 1-100 and to add black border to one of 5 rectangles each representing a range of numbers (0-20, 20-40, etc). Unfortunately, the rectangles are highlighted randomly and don’t appear to be tied to the generated number
Here what I wrote. How do I make this work properly?
const makeNumber = () => {
const randomValue = Math.trunc(Math.random() * 100 + 1);
return randomValue;
};
test.addEventListener("click", function() {
h1.innerText = makeNumber();
statValue();
});
function remove() {
stat.forEach((stat) => {
stat.classList.remove("my-class");
gif.style.visibility = "hidden";
});
}
function statValue() {
if (makeNumber() <= 20) {
remove();
normal.classList.add("my-class");
} else if (makeNumber() > 20 && makeNumber() <= 40) {
remove();
stable.classList.add("my-class");
} else if (makeNumber() > 40 && makeNumber() <= 60) {
remove();
warning.classList.add("my-class");
} else if (makeNumber() > 60 && makeNumber() <= 80) {
remove();
overload.classList.add("my-class");
} else if (makeNumber() > 80) {
remove();
critical.classList.add("my-class");
gif.style.visibility = "visible";
}
}
.my-class {
border: 3px solid black;
}
<div class="container">
<div class="meter">
<div class="stat normal"></div>
<div class="stat stable"></div>
<div class="stat warning"></div>
<div class="stat overload"></div>
<div class="stat critical"></div>
<img class="gif" src="img/Blinking_warning.gif" alt="">
</div>
<h1>0</h1>
<button class="btn">test</button>
</div>
4
Answers
This might be an issue of the way you’re naming the classes in your HTML file. I’m not really understanding what you are asking here.
Why are calling
makeNumber()
every time, everywhere? You need to save output of themakeNumber()
in a variable and then run the loops against that variable. BecausemakeNumber()
is being called in everyif-else
statement, it is generating new different random number and checking the new number against the condition. This is bound to give weird results.You have assigned the output of
makeNumber()
to h1.innerHtml(??), but you are running if-elses with the function itself.Try This
Instead of calling
makeNumber()
every time instatValue()
, you can parse the created number from the click event. You can try this.