jqPlot – Clickable Bar Graphs
I’ve been creating several charts using jqPlot and several of them have been bar graphs. One issue I ran into early on was how to I determine which bar someone clicked on without actually clicking on the data point at the top of the bar.
Updated – Clicking on the image will take you a live example.

My solution does not actually care if the user clicks within the bar. For ease of use, I created my functions to determine which column of the x axis the user clicked in.
line1 = [['Column 1', 99], ['Column 2', 43], ['Column 3', 38], ... ['Column 9', 699]];
// .... Create Bar Graph //
function myClickHandler(ev, gridpos, datapos, neighbor, plot) {
// The length of my array line1 will tell me how many columns I have on my chart.
var column = getColumnLocation(plot,gridpos,line1.length);
}
function getColumnLocation(plot,gridpos,length)
{
// Get the width of the graph area minus the space taken up with axises.
var insidewidth = plot.grid._width;
var colwidth = insidewidth / length;
var column = parseInt(gridpos.x / colwidth);
return column;
}
For another chart, I had multiple bars per axis column and I wanted to know which bar in that column had been clicked on.
Updated – Clicking on the image will take you a live example.

// For this chart I create an array and store each series in it.
barlines[0] = [0, 4, 3, 1, ...];
barlines[1] = [1, 2, 3, 0, ...];
// I need to know the column the user clicked in.
var column = getColumnLocation(plot,gridpos,barlines[0].length);
var bar = getBarLocation(plot,gridpos,barLines.length,barlines[0].length,column);
function getBarLocation(plot, gridpos, bars, length, column)
{
var insidewidth = plot.grid._width;
var colwidth = insidewidth / length;
// I need to find the right and left sides of the column the user clicked on.
var leftx = colwidth * column;
var rightx = colwidth * (column+1);
var left = 0;
var right = 0;
// I need to determine how wide each individual bar is.
var barwidth = colwidth / bars;
var bar = 0;
var j = 0;
for(i=leftx;i< gridpos.x && gridpos.x < i+barwidth ) {
// if the X coordinate falls within the walls of the bar then that's the one I want
bar = j;
}
j++;
}
return bar;
}
So now when the user clicks on the orange bar, they will get the results tied to that bar. I hope this helps someone having the same issue.




Any chance of you posting some valid javascript, and showing it in its full context? Not very helpful at the moment