How to Add a Tooltip to a Flot jQuery Graph CodeUnit 30 DEC 2009

Flot is a fantastic jQuery-driven graphing engine that is extremely flexible and capable of producing some wonderfully looking and interactive graphs.

Today’s quick tutorial looks at how one can add a tooltip to a flot-produced graph.

The secret here is to bind our tooltip generating function to Flot’s built in mouse hover event, firstly removing any tooltip that may already be in existence, generating the new tooltip and attaching it on top of the graph canvas at the correct point.

First we start off by defining our tooltip generating javascript function:

function showChartTooltip(x, y, contents) {
;' + contents + '
;').css( { position: 'absolute', display: 'none', top: y + 5, left: x + 5, border: '1px solid #bfbfbf', padding: '2px', 'background-color': '#ffffff', opacity: 1 }).appendTo("body").fadeIn(200); }

You’ll notice that all we are doing is creating a div, styling it, setting it’s correct x and y co-ordinates in order to correspond to the graph hover position supplied, and then appending it to the main DOM via a jQuery call to append it to the “body” element. As an afterthought and just to make it look nice, we’re using jQuery’s nice little fadeIn functionality to bring the tooltip into view.

Now for the actual meat of the process. What we are going to do is specific the code that needs to be triggered on mouseover (which will call the tooltip drawing function specified above) and bind it to the built in flot plothover event.

$("#graphdivid").bind("plothover", function (event, pos, item) {
if (item) {
var x = item.datapoint[0].toFixed(2),
y = item.datapoint[1].toFixed(2);
showChartTooltip(item.pageX, item.pageY,'tooltip text to display');
} else {

Binding the plothover event to the graph with id graphdivid, we firstly calculate the current X and Y co-ordinates from the event, check that the result is valid, remove any existing tooltip and then call the tooltip drawing function.

And that’s it. Really simple code in order to achieve quite a useful result!

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.