How to Add a Click-through Event on a jQuery Flot Graph CodeUnit 31 DEC 2009

I mentioned Flot, the brilliant little jQuery-driven graphing engine that is extremely flexible and capable of producing some wonderfully looking and interactive graphs, before, but seeing as I’m currently using it as my graphing engine of choice on all of my current Touchwork projects, it makes sense to run another quick tutorial featuring it.

Today I quickly want to touch on adding a click-through event to a Flot graph, in other words, force the browser to redirect to a new location depending on where on the graph the user clicks.

Note, that for this to work, you need to ensure that both the bars and grid declarations feature the clickable: true setting. Obviously not setting this when calling Flot’s plot function will cause the following code to fall flat:

$("#graphdivid").bind("plotclick", function (event, pos, item) {
if (item) {
window.location = "http://url-to-redirect-to.co.za";
}
});

As you can see above, adding a click-through is particularly easy stuff. Simply bind the built in plotclick function to your graph’s div ID and then run a window.location should the click prove to be valid, i.e. item isn’t null.

Of course, to do something specific to the dataset you clicked on, you could always do a switch on say the data series’ label contained in the item object and run code accordingly depending on the switch result:

switch(item.series.label)
{
//do something based on switch
}

So in other words, an extremely simple bit of work for a decent outcome well worth it! :)

Today I quickly want to touch on adding a click-through event to a Flot graph, in other words, force the browser to redirect to a new location depending on where on the graph the user clicks.
Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.

  • Swar

    Thank you for this tutorial, but it would be much improved if you included a working demo of your clickable graph, rather than just a screenshot of it!

  • Swar

    Thank you for this tutorial, but it would be much improved if you included a working demo of your clickable graph, rather than just a screenshot of it!

  • Sorry about that Swar, next time I’ll whip up a demo page to join the tutorial. Didn’t think of it, but thanks for the good idea! :)

  • Sorry about that Swar, next time I’ll whip up a demo page to join the tutorial. Didn’t think of it, but thanks for the good idea! :)

  • Jason

    Thanks