Barchart Routine
Feb 23, 2004Nowhere as complex as some of the scripts posted in this section, but just a little one I wrote. You just use three lines to create and render the barchart:
<html>
<head>
<title>Bar Charts</title>
<style>
.barchart {
table-layout:fixed;
font:normal normal normal small normal monospace;
}
.bar {
position:relative;
margin-bottom:0px;
width:45px;
background-color:#999999;
}
</style>
<script>
function Barchart(id) {
var entries=new Array();
var maxHeight=0;
var absoluteMax=300;
this.setEntries=function() {
for (i=0;i<arguments.length;i+=2) {
entries[i/2]=new Array();
entries[i/2][0]=arguments[i];
if (!isNaN(arguments[i+1])) {
entries[i/2][1]=arguments[i+1];// COULD USE toPrecision() for newer
maxHeight=(entries[i/2][1]>maxHeight)?entries[i/2][1]:maxHeight;
} else {
throw "Value of parameter "+(i+1)*1+" is not a number";
}
}
};
this.toString=function() {
var str="<table id='"+id+"' class='barchart' cellpadding=Ɖ' cellspacing=Ɔ' border=Ɔ'>"+
"<tr valign='bottom' align='center'>";
for (i=0;i<entries.length;i++) {
var h=parseInt((entries[i][1]/maxHeight)*absoluteMax)
str+="<td width=཮' valign='bottom' align='center'>"+entries[i][1]+
"<div class='bar' style='height:"+h+";background-color:"+Barchart.colors[i%Barchart.colors.length]+"'></div></td>";
}
str+="</tr><tr align='center'>";
for (i=0;i<entries.length;i++) {
str+="<td width=཮' align='center'>"+entries[i][0]+"</td>";
}
str+="</tr></table>";
return str;
};
}
Barchart.colors=new Array();
Barchart.colors[0]="blue";
Barchart.colors[1]="green";
Barchart.colors[2]="purple";
Barchart.colors[3]="brown";
</script>
</head>
<body>
Test Page for Bar Charts<br><br>
<script>
// THE CALL TO CREATE AND RENDER THE BARCHART IS BELOW - 3 LINES
var b=new Barchart();
b.setEntries("Anton", 30, "Angela", 55, "Cecile", 24, "Leon", 64, "Rosie", 18);
document.write(b);
</script>
</body>
</html>