Having an issue with changing classes. I can get it to work if I hardcode pixels into the style change but wanted a cleaner version using classes and CSS. The goal is to have the pixel change sizes larger and smaller due to the value of healthPercent in width. This part works but the trouble part is changing the classes to change the color of the bar. For some reason, it does not pass through the if statements correctly and just stays green until death (zero or less for healthPercent), when it reaches zero and then turns red. I can't quite figure out why it passes through the first if check but not the rest. Any ideas on how to fix this?
EDIT: I'm working on a game. just to clarify.
JAVASCRIPT
displayLifeBar = function ()
{
pixelMod = 2.3; //added definition here but global on full code
healthPercent = 130; //added here for example but passed down
lifeBar = 'player_lifebar';
document.getElementById(lifeBar).style.width = healthPercent + 'px';
var criticalLife = 25 * pixelMod;
var lowLife = 50 * pixelMod;
var hurtLife = 75 * pixelMod;
if (healthPercent <= 0){
document.getElementById(lifeBar).className = '';
}
else if (healthPercent < criticalLife){
document.getElementById(lifeBar).className = 'lifebar critical';
}
else if (healthPercent < lowLife){
document.getElementById(lifeBar).className = 'lifebar low';
}
else if (healthPercent < hurtLife){
document.getElementById(lifeBar).className = 'lifebar hurt';
}
else
{
document.getElementById(lifeBar).className = 'lifebar';
}
}
CSS
/* LIFEBAR COLORS STARTS */
.lifebar{
height:20px;
background-color: forestgreen;
}
.lifebar.hurt{
background-color: gold;
}
.lifebar.low{
background-color: orange;
}
.lifebar.critical{
background-color: red;
}
/* LIFEBAR COLORS ENDS */
just stays green until death, when it reaches zero and then turns red
. – Mamun