JQuery

Greetings All! Since everyone was digging the Star Comment Rating I decided that I would give this animated JQuery Bar Chart out too. I’ve been holding onto it for a while, it is now yours for the taking.

This tutorial is a little lengthy, so if you need to get a coffee or use the restroom, we’ll wait.

Your back, good. Here is the Animated JQuery Bar Chart that we will be making:


SKIP TO FINISHED CODE or DOWNLOAD IT

Not too long ago I had a client dashboard that was in need of a bar chart. Of course there are many plugins out there for javascript charts and even flash. Since I like to know how things work before I stick them on a site I decided to make my animated bar chart from JQuery. The nice thing about this one is that it uses only:

  • Basic HTML
  • CSS
  • Javascript & JQuery

To make it easier for tutorials purposes I broke the javascript down into functions and use a JavaScript Object to hold all of the necessary parameters for making the chart. If you’re new to objects don’t worry it is pretty easy.

For this tutorial, all we need is one HTML document and the latest JQuery called into the page in the <head> tag. I’m using version 1.4.2.

Google hosted JQuery Code for Bar Chart

Google hosted JQuery Code for Bar Chart

Ok. Let’s get started.

Hopefully you have your HTML editor open and the JQuery added. If not, what’s taking you so darn long!!! Its ok, we will all wait on you.

Once you have the above we are going to move onto a quick run down of javascript objects and why I am using them for this tutorial. You ready?

JAVASCRIPT OBJECTS. By Reference or By Value

When using a normal variable such as a string or a int(aka number) these are used by Value. Meaning, when you have a variable, let’s say $x just for example purposes, and we say, $x = 0. But then we create a function named — exampleFunction(){ $x=2 } and put $x inside of it and assign it the value of 2.

The first $x still stays 0 because it is outside of that scope. Meaning it uses two separate spaces in memory for this. When using arrays or objects in JavaScript it is by Reference. Meaning it uses one space in memory for that name.
Quick Example: $myarray = new Array(‘1’,’2’,’3’); then we have a function –exampleFunction(){ $myArray – still equals what it was outside of the funciton }.

Now it is the same for objects, but objects have properties which helps organize things. $v = new Object(); $v always stays there in the life of that page until you delete it, save over it, or refresh the page. Got it?

Now that you know a little bit about Objects let’s move on!

When making a graph one should usually start with a design on the page and know what size you want it to be in height and width. That’s why this graph we are going to make is so cool. You set the height and width in the css and your graph grows and stretches accordingly.

There is a catch though. In order to make it pretty we need to make the height and width divisible by certain things which I will show you in a bit.

So let’s start off with the HTML.

A chart has two main things, the chart itself and a legend. I am using a table to house both of them. The first <td> will have the div’s for the chart/graph itself and the second <td> will have the legend and values or the chart to pull from.

Here it is, I will explain what is inside the td’s next.

<table id="testgraph" class="graphtable">
 <tr>
 <td>
 <div class="gCont">   <div class="graph"></div>   </div>
 </td>
 <td class="values">
 <label>First Number:<span style="background-color: #06F;">34</span></label>
 <label>Second Number:<span style="background-color: #C60;">20</span></label>
 <label>Third Number:<span style="background-color: #936;">15</span></label>
 <label>Fourth Number:<span style="background-color: #96C;">30</span></label>
 <label>Fifth Number:<span style="background-color: #396;">18</span></label>
 </td>
 </tr>
</table>

Notice the <table> has an ID of “graph1”. Can anyone tell me why? Yes, you in the back with the overly tight horizontally striped shirt that can’t quite seem to totally cover your stomach. Ummm. Yes, you are correct. We can have more than one graph on a page! But there are some things you have to do to make two graphs work, which I will go over at the end. (hint: save over the old $v object with next graphs settigns), ok let’s get back on track.

The first TD, our chart/graph:

We have one div with the class of .gCont (guess what that stands for? Yup! Graph Container!! Amazing). Then just inside that we have a div with the class of .graph, that is exactly what that stands for.

We are going to put the bars to the chart just after the .graph div, but just inside the .gCont! The lines and the numbers for the graph will go inside the .graph div. This is all done with JQuery, but we will get to that after I explain the legend/values and all the css to make it presentable.

The second TD, our legend/values:

On this td, we put a class of .values. Then inside it we put a <label> with the name of whatever we’re graphing for that bar and then a <span> with the actual value and style with the background color we want for that bar. Each <label> is one bar on the chart. You can add as many as you like, but if you add too many it will eventually look like crap depending on how big your height and width is on your chart. I put 5 on there for this tutorial.

Our JQuery, will look into this TD and loop through all the labels to make the BARS for the chart. Oh, and I used fixed widths in the css for the layout of legend, so you will have to play with it if you are going to put really large numbers or text in them.

.graphtable td { vertical-align: top; font-family: Arial, Helvetica, sans-serif; }
 .graphtable label { display: block; width: 145px; height: 25px; font-size: 13px; padding-left: 35px; }
 .graphtable label span { display: block; width: 55px; float: right; height: 15px; width: 15px;  border: 1px solid #ccc; text-indent: -20px;  }
 .line { font-size: 10px; }
 .graph { margin-left: 35px; border: 1px solid #666; }
 .graph .line { border-bottom: 1px solid #ccc; margin-top: -1px; }
 .graph .fix  { border-bottom: none;}
 
 .graph .line span { position: absolute; display: block; margin-left: -40px; width: 35px; text-align: right; margin-top: -5px; }
 .bar { position: absolute; margin-bottom: 0; }

What?! You’ve probably refreshed your HTML and noticed it doesn’t quite look right. That’s because we haven’t put a height and width on our “#graph1 .graph”. Here is what that looks like:

#graph1 .graph {
 height: 170px; /* Needs to be divisible by Number of Graph lines, IE & Chrome will round down decimals in CSS. FF will use the decimals. */
 width: 300px; /* Needs to be divisible by number of Bars, if you want them to be centered nicely */
 }

So now that you have refreshed, everything should look like a graph without lines, hopefully. If not, you can always just download the finished code at the end of the page along with all the other lazy people who didn’t read this far and already skipped to the code. (They know who they are. Everyone help direct scolding looks their way.)

We are now ready to get into the FUN STUFF! Hurray!!!!! I am going to show you my stamp collection, oh, wait, wrong site. I meant JQuery and JavaScript!

JQUERY & JAVSCRIPT

Here is the user input, meaning you, which we need to start the graph.

  • The id for the table |sting|
  • Number of lines in the graph |int| (warning, leave it at ten, unless you want a mess)
  • Animate it |bool |(set to false if you have more than one graph on the page)
  • Animation Speed |int| (how fast the bars grow in milliseconds)

The Initial Values:

$graph_id    = 'graph1'; // id of graph container
 $lines       = 10; // number of lines - keep this 10 unless you want to write a bunch more code
 $bar_margins = 30; // margins between the bars
 $bar_speed   = 500; // speed for bar animation in milliseconds
 $animate     = true; // set to false if multiple charts on one page
 graphit($graph_id,$lines,$bar_margins,$bar_speed, $animate);

The First Function: graphIt()

Inside of the graphId() function is where we create our object and all the values. I have commented next to each one which explains what it does. You do not need to edit anything here at all, only in the Initial values passed in. Notice inside this function after all the object parameters we have the function getValues(), graphLines(), graphBars() , and animateBars(0). We are going to make all these next.

/**
 * Initiates Graph Functions
 **/
 function graphit($graph_id,$lines,$bar_margins,$bar_speed,$animate){
 
 $v = new Object(); // create graph object
 $v.graphid = $graph_id; // id of graph container, example "graph1" or "myGraph"
 $v.values = new Array(); // array of values
 $v.heights = new Array(); // array of bar heights
 $v.colors = new Array(); // colors for bars
 $v.lines = $lines; // number of lines - keep this 10 unless you want to write a bunch more code
 $v.bm = $bar_margins; // margins between the bars
 $v.mx = 0; // highest number, or rounded up number
 $v.gw = $('#'+$v.graphid+' .graph').width(); // graph width
 $v.gh = $('#'+$v.graphid+' .graph').height(); // graph height
 $v.speed = $bar_speed; // speed for bar animation in milliseconds
 $v.animate = $animate; // determines if animation on bars are run, set to FALSE if multiple charts
 
 getValues(); // load the values & colors for bars into $v object
 graphLines(); // makes the lines for the chart
 graphBars(); // make the bars
 if($v.animate)
 animateBars(0); // animate and show the bars
 }

The Second Function: getValues()

If you haven’t noticed yet I try to name my functions accordingly to what they do and not some trivial puzzle like some programmers who think they are overly clever. This function does just that, it loops through the legend span’s and gets the numbers inside and the colors for each one. It assigns them to the $v object in $v.colors and $v.values. Take a look.

/**
 * Gets the values & colors from the HTML <labels> and saves them into $v ohject
 **/
 function getValues(){
 $lbls = $('#'+$v.graphid+' .values span'); // assigns the span DOM object to be looped through
 // loop through
 for($i=0;$i <= $lbls.length-1; $i++){
 $vals = parseFloat($lbls.eq($i).text());
 $v.colors.push($lbls.eq($i).css('background-color'));
 $v.mx = ($vals > $v.mx)?$vals:$v.mx;
 $v.values.push($vals);
 }
 }

Notice that I am not using the JQuery .each function to loop through the spans, but instead assigning the DOM nodes to the value $lbl. I feel that when doing tasks as this a developer can have more control and freedom when doing it this way. For more on this you can view While Loops With JQuery. Ok so now have the numbers and colors assigned to our object $v.

The Third Functions: graphLines() & graphLinesHelper() & roundUp()

This function makes the lines and numbers on our bar chart. This is where we do all the math based on the height we set in the css, divide it by the number of lines we set in the initial setup with $lines.

There are two other functions called inside this one. The first is roundUp($n,$r), it is a simple round up function so we can set the max number on the chart lines.
The other function inside the while loop called graphLinesHelper($i, $v.mx). This is created just to ease the mess out of the loop in creating the HTML for the lines and graph numbers themselves. Inside the helper function we add a class called .fix which takes off the border for the first and last chart line.

After we looped through, created, and inserted the HTML for the lines inside .graph we add the necessary margins to space them evenly.

/**
 * Makes the HTML for the lines on the chart, and places them into the page.
 **/
 function graphLines(){
 $r = ($v.mx < 100)?10:100; // determine to round up to 10 or 100
 $v.mx = roundUp($v.mx,$r); // round up to get the max number for lines on chart
 $d = $v.mx / $v.lines; // determines the increment for the chart line numbers    
 
 // Loop through and create the html for the divs that will make up the lines & numbers
 $html = ""; $i = $v.mx;
 if($i>0 && $d>0){
 while($i >= 0){
 $html += graphLinesHelper($i, $v.mx);
 $i = $i - $d;
 }
 }
 $('#'+$v.graphid+' .graph').html($html); // Put the lines into the html
 $margin = $v.gh / $v.lines; // Determine the margin size for line spacing
 $('#'+$v.graphid+' .line').css("margin-bottom",$margin + "px");    // Add the margins to the lines
 }
 
 /**
 * Creates the html for the graph lines and numbers
 **/
 function graphLinesHelper($num, $maxNum){
 $fix = ($i == $maxNum || $i == 0)? "fix ":""; // adds class .fix, which removes the "border" for top and bottom lines
 return "<div class='"+$fix+"line'><span>" + $num + "</span></div>";
 }
 
 /**
 * A Simple Round Up Function
 **/
 function roundUp($n,$r){
 return (($n%$r) > 0)?$n-($n%$r) + $r:$n;
 }

The Fourth Function: graphBars()

This is where the bars will be create for the chart. We do all the math to space them properly based on the width you put in the css and determine the height they will be based on the value you have in your legend. If $animate was set to TRUE it sets the height to 0px until the next function, animateBars(), but if it is set to FALSE then it will just put the height in for no effect. Once all the HTML is created with the heights and margins, we insert into the .gCont right after the .graph.

/**
 * Creates the HTML for the Bars, adds colors, widths, and margins for proper spacing.
 * Then Puts it on the page.
 **/
 function graphBars(){
 $xbars  = $v.values.length; // number of bars
 $barW    = ($v.gw-($xbars * ($v.bm))) / $xbars;
 $mL     = ($('#'+$v.graphid+' .line span').width()) + ($v.bm/2);
 $html="";
 for($i=1;$i<=$xbars;$i++){
 $v.heights.push(($v.gh / $v.mx) * $v.values[$i-1]);
 $ht = ($v.animate == true)?0:$v.heights[$i-1];
 $html += "<div class='bar' id='"+$v.graphid+"_bar_"+($i-1)+"' style='height: "+$ht+"px; margin-top: -"+($ht+1)+"px; ";
 $html += "background-color: "+$v.colors[$i-1]+"; margin-left: "+$mL+"px'>&nbsp;</div>";
 $mL = $mL + $barW + $v.bm;
 }
 $($html).insertAfter('#'+$v.graphid+' .graph');
 $('#'+$v.graphid+' .bar').css("width", $barW + "px");
 }

The Fifth Function: optional animateBars():

Here is where we use the JQuery animate method to grow the height and the negative top margin. We also enter a callback function of itself so it does one bar at a time.

/**
 * Animates the Bars to the correct heights.
 **/
 function animateBars($i){
 if($i == $v.values.length){ return; }
 $('#'+$v.graphid+'_bar_'+$i).animate({
 marginTop: "-" + ($v.heights[$i] + 1) + "px",
 height: ($v.heights[$i]) + "px"
 },$v.speed,"swing", function(){animateBars($i+1); });
 }

And that’s it, we’re done! Woot! Now, there is a little side note on where the functions should be placed. You can put all the functions we just made into an external javascript file or in the header of the page, as long as it is after the JQuery library. But when creating the Initial values surrounded with the $document.ready function, I would stick that right above your html, in case you have more than one graph. Example:

All our functions

<head>
// all our functions we created
</head>
 
<body> 
 
<script type=text/javascript”>
 // initial values
//  animate set to false.
 </script>
<table id=”graph1” class=”graphtable”>…….
 <!—our next graph -->
<script type=text/javascript”>
 // initial values for graph 2
</script>
 <table id=”graph2” class=”graphtable”>…….
</body>

Get it?

Here is all the completed code together.

Finished Code :)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Eli Geske's Bar Chart</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style type="text/css">
 /* Graph 1 */
 #testgraph .graph {
 height: 170px; /* Needs to be divisible by Number of Graph lines, IE & Chrome will round down decimals in CSS. FF will use the decimals. */
 width: 300px; /* Needs to be divisible by number of Bars, if you want them to be centered nicely */
 }
 
 .graphtable td { vertical-align: top; font-family: Arial, Helvetica, sans-serif; }
 .graphtable label { display: block; width: 145px; height: 25px; font-size: 13px; padding-left: 35px; }
 .graphtable label span { display: block; width: 55px; float: right; height: 15px; width: 15px;  border: 1px solid #ccc; text-indent: -20px;  }
 .line { font-size: 10px; }
 .graph { margin-left: 35px; border: 1px solid #666; }
 .graph .line { border-bottom: 1px solid #ccc; margin-top: -1px; }
 .graph .fix  { border-bottom: none;}
 
 .graph .line span { position: absolute; display: block; margin-left: -40px; width: 35px; text-align: right; margin-top: -5px; }
 .bar { position: absolute; margin-bottom: 0; }
 
</style>
<script type="text/javascript">
 
 /**
 * Initiates Graph Functions
 **/
 function graphit($graph_id,$lines,$bar_margins,$bar_speed,$animate){
 
 $v = new Object(); // create graph object
 $v.graphid = $graph_id; // id of graph container, example "graph1" or "myGraph"
 $v.values = new Array(); // array of values
 $v.heights = new Array(); // array of bar heights
 $v.colors = new Array(); // colors for bars
 $v.lines = $lines; // number of lines - keep this 10 unless you want to write a bunch more code
 $v.bm = $bar_margins; // margins between the bars
 $v.mx = 0; // highest number, or rounded up number
 $v.gw = $('#'+$v.graphid+' .graph').width(); // graph width
 $v.gh = $('#'+$v.graphid+' .graph').height(); // graph height
 $v.speed = $bar_speed; // speed for bar animation in milliseconds
 $v.animate = $animate; // determines if animation on bars are run, set to FALSE if multiple charts
 
 getValues(); // load the values & colors for bars into $v object
 graphLines(); // makes the lines for the chart
 graphBars(); // make the bars
 if($v.animate)
 animateBars(0); // animate and show the bars
 }
 
 /**
 * Makes the HTML for the lines on the chart, and places them into the page.
 **/
 function graphLines(){
 $r = ($v.mx < 100)?10:100; // determine to round up to 10 or 100
 $v.mx = roundUp($v.mx,$r); // round up to get the max number for lines on chart
 $d = $v.mx / $v.lines; // determines the increment for the chart line numbers    
 
 // Loop through and create the html for the divs that will make up the lines & numbers
 $html = ""; $i = $v.mx;
 if($i>0 && $d>0){
 while($i >= 0){
 $html += graphLinesHelper($i, $v.mx);
 $i = $i - $d;
 }
 }
 $('#'+$v.graphid+' .graph').html($html); // Put the lines into the html
 $margin = $v.gh / $v.lines; // Determine the margin size for line spacing
 $('#'+$v.graphid+' .line').css("margin-bottom",$margin + "px");    // Add the margins to the lines
 }
 
 /**
 * Creates the html for the graph lines and numbers
 **/
 function graphLinesHelper($num, $maxNum){
 $fix = ($i == $maxNum || $i == 0)? "fix ":""; // adds class .fix, which removes the "border" for top and bottom lines
 return "<div class='"+$fix+"line'><span>" + $num + "</span></div>";
 }
 
 /**
 * A Simple Round Up Function
 **/
 function roundUp($n,$r){
 return (($n%$r) > 0)?$n-($n%$r) + $r:$n;
 }
 
 /**
 * Gets the values & colors from the HTML <labels> and saves them into $v ohject
 **/
 function getValues(){
 $lbls = $('#'+$v.graphid+' .values span'); // assigns the span DOM object to be looped through
 // loop through
 for($i=0;$i <= $lbls.length-1; $i++){
 $vals = parseFloat($lbls.eq($i).text());
 $v.colors.push($lbls.eq($i).css('background-color'));
 $v.mx = ($vals > $v.mx)?$vals:$v.mx;
 $v.values.push($vals);
 }
 }
 
 /**
 * Creates the HTML for the Bars, adds colors, widths, and margins for proper spacing.
 * Then Puts it on the page.
 **/
 function graphBars(){
 $xbars  = $v.values.length; // number of bars
 $barW    = ($v.gw-($xbars * ($v.bm))) / $xbars;
 $mL     = ($('#'+$v.graphid+' .line span').width()) + ($v.bm/2);
 $html="";
 for($i=1;$i<=$xbars;$i++){
 $v.heights.push(($v.gh / $v.mx) * $v.values[$i-1]);
 $ht = ($v.animate == true)?0:$v.heights[$i-1];
 $html += "<div class='bar' id='"+$v.graphid+"_bar_"+($i-1)+"' style='height: "+$ht+"px; margin-top: -"+($ht+1)+"px; ";
 $html += "background-color: "+$v.colors[$i-1]+"; margin-left: "+$mL+"px'>&nbsp;</div>";
 $mL = $mL + $barW + $v.bm;
 }
 $($html).insertAfter('#'+$v.graphid+' .graph');
 $('#'+$v.graphid+' .bar').css("width", $barW + "px");
 }
 
 /**
 * Animates the Bars to the correct heights.
 **/
 function animateBars($i){
 if($i == $v.values.length){ return; }
 $('#'+$v.graphid+'_bar_'+$i).animate({
 marginTop: "-" + ($v.heights[$i] + 1) + "px",
 height: ($v.heights[$i]) + "px"
 },$v.speed,"swing", function(){animateBars($i+1); });
 }
 
</script>
 
</head>
<body>
 
<script type="text/javascript">
 $(document).ready(function(){
 $graph_id    = 'testgraph'; // id of graph container
 $lines          = 10; // number of lines - keep this 10 unless you want to write a bunch more code
 $bar_margins = 30; // margins between the bars
 $bar_speed      = 500; // speed for bar animation in milliseconds
 $animate      = true; // set to false if multiple charts on one page
 graphit($graph_id,$lines,$bar_margins,$bar_speed, $animate);
 });
</script>
<table id="testgraph" class="graphtable">
 <tr>
 <td>
 <div class="gCont">   <div class="graph"></div>   </div>
 </td>
 <td class="values">
 <label>First Number:<span style="background-color: #06F;">34</span></label>
 <label>Second Number:<span style="background-color: #C60;">20</span></label>
 <label>Third Number:<span style="background-color: #936;">15</span></label>
 <label>Fourth Number:<span style="background-color: #96C;">30</span></label>
 <label>Fifth Number:<span style="background-color: #396;">18</span></label>
 </td>
 </tr>
</table>
 
</body>
</html>

15 Responses to "Animated JQuery Bar Chart"

"SHARING IS CARING"
  1. kieren says:

    i am 13 and i tried to get that animation at the top of the bar chasrt can u help me do it plz

  2. kieren wood says:

    i am 13 and i tried to get that animation at the top of the bar chasrt can u help me do it plz

    thank u kiueren wood

  3. eligeske says:

    Hi kieuren,

    The email you left is getting kicked back.

  4. zo_h says:

    Very nice Bar Chart

    Some time ago, I did something similar on the my wife homepage. Look at this:

    http://www.gohha.com/o_mnie.html (page footer)

    Very basic HTML, some CSS, transparent PNG and jquery support.

    Regards
    Peter

  5. Sir
    I am very much glad. I am searching this script for a long time.
    Again thaknx

  6. Sam says:

    Hi,
    Can you please tell me how to change the value “0″ in the vertical line of the graph, to the bottom adjacent to the bottom most line of the graph? The scale is not exactly correct.

    Thanks

  7. eligeske says:

    Hey Sam,

    Glad to help, can you send me a link with what you’re working on so I can get a better idea of what issue is?

    Thanks
    Eli

  8. Sam says:

    Hi Eli,
    Thanks for replying. In the same link http://eligeske.com/jquery/animated-jquery-bar-chart/comment-page-1/&#35comment-569, there is Animated JQuery Bar Chart present. I’m pasting the following code and the chart is generating. But i wanna know what changes i’ve to make in this code for the 0 value in the vertical line of the chart to come to the bottommost horizontal line of the chart. As you can see in this link that “0″ doesn’t have any hortizontal line, horizontal lines only start from “4″. I hope i’ve made my doubt clear.

    <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
    <html xmlns=”http://www.w3.org/1999/xhtml”>
    <head>
    <meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
    <title>Eli Geske’s Bar Chart</title>
    <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
    <style type=”text/css”>
    /* Graph 1 */
    &#35testgraph .graph {
    height: 170px; /* Needs to be divisible by Number of Graph lines, IE & Chrome will round down decimals in CSS. FF will use the decimals. */
    width: 300px; /* Needs to be divisible by number of Bars, if you want them to be centered nicely */
    }

    .graphtable td { vertical-align: top; font-family: Arial, Helvetica, sans-serif; }
    .graphtable label { display: block; width: 145px; height: 25px; font-size: 13px; padding-left: 35px; }
    .graphtable label span { display: block; width: 55px; float: right; height: 15px; width: 15px; border: 1px solid &#35ccc; text-indent: -20px; }
    .line { font-size: 10px; }
    .graph { margin-left: 35px; border: 1px solid 譒 }
    .graph .line { border-bottom: 1px solid &#35ccc; margin-top: -1px; }
    .graph .fix { border-bottom: none;}

    .graph .line span { position: absolute; display: block; margin-left: -40px; width: 35px; text-align: right; margin-top: -5px; }
    .bar { position: absolute; margin-bottom: 0; }

    </style>
    <script type=”text/javascript”>

    /**
    * Initiates Graph Functions
    **/
    function graphit($graph_id,$lines,$bar_margins,$bar_speed,$animate){

    $v = new Object(); // create graph object
    $v.graphid = $graph_id; // id of graph container, example “graph1″ or “myGraph”
    $v.values = new Array(); // array of values
    $v.heights = new Array(); // array of bar heights
    $v.colors = new Array(); // colors for bars
    $v.lines = $lines; // number of lines – keep this 10 unless you want to write a bunch more code
    $v.bm = $bar_margins; // margins between the bars
    $v.mx = 0; // highest number, or rounded up number
    $v.gw = $(‘&#35′+$v.graphid+’ .graph’).width(); // graph width
    $v.gh = $(‘&#35′+$v.graphid+’ .graph’).height(); // graph height
    $v.speed = $bar_speed; // speed for bar animation in milliseconds
    $v.animate = $animate; // determines if animation on bars are run, set to FALSE if multiple charts

    getValues(); // load the values & colors for bars into $v object
    graphLines(); // makes the lines for the chart
    graphBars(); // make the bars
    if($v.animate)
    animateBars(0); // animate and show the bars
    }

    /**
    * Makes the HTML for the lines on the chart, and places them into the page.
    **/
    function graphLines(){
    $r = ($v.mx < 100)?10:100; // determine to round up to 10 or 100
    $v.mx = roundUp($v.mx,$r); // round up to get the max number for lines on chart
    $d = $v.mx / $v.lines; // determines the increment for the chart line numbers

    // Loop through and create the html for the divs that will make up the lines & numbers
    $html = “”; $i = $v.mx;
    if($i>0 && $d>0){
    while($i >= 0){
    $html += graphLinesHelper($i, $v.mx);
    $i = $i – $d;
    }
    }
    $(‘&#35′+$v.graphid+’ .graph’).html($html); // Put the lines into the html
    $margin = $v.gh / $v.lines; // Determine the margin size for line spacing
    $(‘&#35′+$v.graphid+’ .line’).css(“margin-bottom”,$margin + “px”); // Add the margins to the lines
    }

    /**
    * Creates the html for the graph lines and numbers
    **/
    function graphLinesHelper($num, $maxNum){
    $fix = ($i == $maxNum || $i == 0)? “fix “:”"; // adds class .fix, which removes the “border” for top and bottom lines
    return “<div class=’”+$fix+”line’><span>” + $num + “</span></div>”;
    }

    /**
    * A Simple Round Up Function
    **/
    function roundUp($n,$r){
    return (($n&#37$r) > 0)?$n-($n&#37$r) + $r:$n;
    }

    /**
    * Gets the values & colors from the HTML <labels> and saves them into $v ohject
    **/
    function getValues(){
    $lbls = $(‘&#35′+$v.graphid+’ .values span’); // assigns the span DOM object to be looped through
    // loop through
    for($i=0;$i <= $lbls.length-1; $i++){
    $vals = parseFloat($lbls.eq($i).text());
    $v.colors.push($lbls.eq($i).css(‘background-color’));
    $v.mx = ($vals > $v.mx)?$vals:$v.mx;
    $v.values.push($vals);
    }
    }

    /**
    * Creates the HTML for the Bars, adds colors, widths, and margins for proper spacing.
    * Then Puts it on the page.
    **/
    function graphBars(){
    $xbars = $v.values.length; // number of bars
    $barW = ($v.gw-($xbars * ($v.bm))) / $xbars;
    $mL = ($(‘&#35′+$v.graphid+’ .line span’).width()) + ($v.bm/2);
    $html=”";
    for($i=1;$i<=$xbars;$i++){
    $v.heights.push(($v.gh / $v.mx) * $v.values[$i-1]);
    $ht = ($v.animate == true)?0:$v.heights[$i-1];
    $html += “<div class=’bar’ id=’”+$v.graphid+”_bar_”+($i-1)+”‘ style=’height: “+$ht+”px; margin-top: -”+($ht+1)+”px; “;
    $html += “background-color: “+$v.colors[$i-1]+”; margin-left: “+$mL+”px’>&nbsp;</div>”;
    $mL = $mL + $barW + $v.bm;
    }
    $($html).insertAfter(‘&#35′+$v.graphid+’ .graph’);
    $(‘&#35′+$v.graphid+’ .bar’).css(“width”, $barW + “px”);
    }

    /**
    * Animates the Bars to the correct heights.
    **/
    function animateBars($i){
    if($i == $v.values.length){ return; }
    $(‘&#35′+$v.graphid+’_bar_’+$i).animate({
    marginTop: “-” + ($v.heights[$i] + 1) + “px”,
    height: ($v.heights[$i]) + “px”
    },$v.speed,”swing”, function(){animateBars($i+1); });
    }

    </script>

    </head>
    <body>

    <script type=”text/javascript”>
    $(document).ready(function(){
    $graph_id = ‘testgraph’; // id of graph container
    $lines = 10; // number of lines – keep this 10 unless you want to write a bunch more code
    $bar_margins = 30; // margins between the bars
    $bar_speed = 500; // speed for bar animation in milliseconds
    $animate = true; // set to false if multiple charts on one page
    graphit($graph_id,$lines,$bar_margins,$bar_speed, $animate);
    });
    </script>
    <table id=”testgraph” class=”graphtable”>
    <tr>
    <td>
    <div class=”gCont”> <div class=”graph”></div> </div>
    </td>
    <td class=”values”>
    <label>First Number:<span style=”background-color: &#3506F;”>34</span></label>
    <label>Second Number:<span style=”background-color: &#35C60;”>20</span></label>
    <label>Third Number:<span style=”background-color: 豠”>15</span></label>
    <label>Fourth Number:<span style=”background-color: &#3596C;”>30</span></label>
    <label>Fifth Number:<span style=”background-color: 詄”>18</span></label>
    </td>
    </tr>
    </table>

    </body>
    </html>

  9. eligeske says:

    Hi Sam,

    I tried the email you provided to request the file.

    Just in case that was the incorrect email address, here is my findings:

    - the html pasted above is hard to tell with the special characters after wordpress transformed it.

    You can try this changing the css for .graph to :

    .graph {
    margin-left: 35px;
    border-bottom: 1px solid #ccc;
    border-top: 1px solid #ccc;
    }

    What browser are you using?

  10. Sam says:

    Hi,
    Sorry about the confusion with the email id. Actually the code works perfectly fine with only google chrome. It creates a problem with IE8 (when the value is 0, the bar in the chart shows a negative value and does not raise up). But i need the code to work on any browser. Thanks a ton for the help :-)

    Sam

  11. eligeske says:

    Hey Sam,

    Thanks for clarification on your problem. I’ll take a look into it and get back with you.

  12. Ajmal says:

    negative values are not displayed – pls add how it can be displayed

  13. eligeske says:

    Hi Ajmal,

    Sorry didn’t really plan on using it for negative numbers.

    But I’m sure with a little tinkering around someone may be able to get it to use them.

  14. Benoit says:

    Im trying to make the animation start with a button but it doesnt work ! could you help me ?

    $(“#button”).click(function(){
    $graph_id = ‘testgraph’; // id of graph container
    $lines = 10; // number of lines –
    $bar_margins = 30; // margins between the bars
    $bar_speed = 500; // speed for bar animation in milliseconds
    $animate = true; // set to false if multiple charts on one page
    graphit($graph_id,$lines,$bar_margins,$bar_speed, $animate);
    });

    thanks

  15. eligeske says:

    Hi Benoit,

    I have updated the download zip with a new file called BarChart_New. The code is now restructured in that file to a re-usable class and if animation is set to true, you must run the animateBars() function to show the bars. This way you can add it to an event, such as “onClick”.

    Hope this helps.

    Eli

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Learning DHTMLX Suite UI

Learn the foundation of the DHTMLX Suite quickly while building a single page application with multiple components in harmony.

Popular post