jQuery Scrolling Bar Graph


Fork me on GitHub

As part of a project written in Grails to analyse the SMS messages which came into the BBC Radio studio, I put together a user interface in Javascript that showed the incoming rate of messages. It presented this as a scrolling bar graph, which you can get here.

Here's a quick demo of it working, using a random number generator:

You can see that the y-axis and the bar scaling is dependent on the maximum value bar that's visible in the window. Internally, the widget is only storing the data that is displayed.

To use it, you first need to include a few other javascript libraries. In particular, you require jQuery and the jQuery widget factory, but the code also uses canvas_utils.js (for drawing polygons) and jquery.timers (for its animation).

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script type="text/javascript" src="/js/canvas_utils.js"></script>
<script type="text/javascript" src="/js/jquery.timers-1.2.js"></script>
<script type="text/javascript" src="/js/SlidingBarGraphWidget-1.0.js"></script>

Create an element in the page and then apply the bargraph widget to it, just as you would with any jQuery widget:

<div id="graph"></div>
<script type="text/javascript">

The graph can then be added to using the setData method on the widget. This takes an array of numbers to add to the graph. You can add one at a time or in batch. For example, to slide a bar with the value 10 onto the side use the following:

$('#graph').bargraph( 'setData', [10] );

The method still expects an array, so you have to create an array of one value. Or to slide 4 bars on use this:

$('#graph').bargraph( 'setData', [5,6,7,8] );

The setup of the graph can be altered during its construction in the usual way, passing in values in an object. For example, the graph colours can be altered and a line drawn between bars:

	style: "line & filledbar",
	dataPointStyle: "filledCircle",
	barFillStyle: '#0F0',
	barStrokeStyle: '#FFF',
	barStrokeWidth: 2,
	dataPointStrokeStyle: '#FFF'

The code to produce the random graphs, like the ones seen above, is this:

// This updates the graphs every second with random values
$(document).everyTime( 1000, function()
	$('#graph').bargraph('setData', [Math.random()*10] );
}, 0 );


You can fork the code on GitHub.


The code is released under the MIT license, which basically means you can do whatever you like except pretend it's yours.