In one of my previous articles on GridViewGuy I demonstrated a technique to draw bar charts using the .NET graphics API. You can check out the article here. Although the article did served a purpose of drawing attractive charts but the processing was performed on the server side.
For simple graphs this technique would not posses a problem but as soon as the users start generating several graphs this will put immense load on the server. I have a post on profiling .NET applications in which I created Polygons with different sides and measured the effect of sides on the application as a whole. You can view the article here.
In this post I will create the bar charts on the client side. This technique is implemented with the idea that the client computer is sitting at 2% memory consumption most of the time. Why not use that memory to perform actions that were performed on the server side? And since we are performing this action on the client side why not use JQuery library to create some cool animation effects.
Let’s start by creating the elements on the page which includes the Button control and few DIVS.
<input type="button" id="btn1" value="draw" />
<div class="container">
<div id="placeHolderDiv" class="placeHolder" > </div>
<div id="baseDiv" class="base"></div>
</div>
The purpose of the placeHolderDiv and the baseDiv is to just mark the bottom and top of the box in which to create the bar graph.

Now, let’s check out the code which creates and animates the graph.
function drawGraph()
{
$("#baseDiv").children(".barStyle").remove();
marginLeft = 0;
for(i=1;i<=10;i++) {
var bar = document.createElement("div");
bar.id = 'bar' + i;
bar.className = 'barStyle';
marginLeft += 25;
bar.style.bottom = '4px';
bar.style.left = marginLeft + 'px';
// generate a random number
var randomNumber = Math.random();
randomNumber = Math.ceil(randomNumber * 100);
barH = (randomNumber) + 'px';
$("#baseDiv").append(bar);
$("#" + bar.id).animate(
{
height:barH
}
,1200);
}
The JavaScript random function is used to supply random height to the bar chart. The JQuery animate function makes it possible to create cool animation of the graph. If you are new to JQuery animation then I recommend that you check out this introductory screencast about JQuery animation.
The effect is shown below:

Pretty slick right!
[Download Sample]