March 22, 2012
Percentage to change div width in JS
Question by Dave
I have a very basic script that calculates and changes the width of a div but its not working it keeps giving a 100 % result .
My script is like this:
<script>
var hp = <? echo $row['hp']; ?>;
var max = <? echo $row['maxhp']; ?>;
var perc = Math.round(hp/max * 100);
if(perc > 100) perc = 100;
else if(perc < 0 ) perc = 0;
d = document.getElementById('health');
d.style.width= perc+"%";
</script>
<div id="health" style="background-color:green;min-height:5px;"></div>
The PHP numbers are showing correct in the JS as:
var hp = 500;
var max = 2500;
Any ideas why it might not be working ?
Answer by Derek
You have to wait until the document (DOM) to load first.
//head
$(function(){ //same as "onload" (jQuery)
var hp = 500,
max = 2500,
perc = Math.round(hp/max * 100);
if(perc > 100){
perc = 100;
}else if(perc < 0 ){
perc = 0;
}
//have to wait until DOM loaded, or else it return "not found"
d = document.getElementById('health');
d.style.width= perc+"%";
alert(perc+"%");
});
Answer by Starx
Its working, see a demo
So, the problem is the script is running before the element is loaded on the DOM. Put the script after the HTML
<div id="health" style="background-color:green;min-height:5px;"></div>
<script>
var hp = <? echo $row['hp']; ?>;
var max = <? echo $row['maxhp']; ?>;
var perc = Math.round(hp/max * 100);
if(perc > 100) perc = 100;
else if(perc < 0 ) perc = 0;
d = document.getElementById('health');
d.style.width= perc+"%";
</script>