Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Sep 2002
    Location
    Surrey, UK
    Posts
    119
    Thanks
    0
    Thanked 0 Times in 0 Posts

    barchart routine

    Nowhere 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='3' cellspacing='0' border='0'>"+
    "<tr valign='bottom' align='center'>";
    for (i=0;i<entries.length;i++) {
    var h=parseInt((entries[i][1]/maxHeight)*absoluteMax)
    str+="<td width='50' 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='50' 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>

  2. #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    19,058
    Thanks
    211
    Thanked 2,642 Times in 2,620 Posts
    Thanks for that, ahosang! Very useful indeed.


 

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •