Unique Tooltips per Point using Flot

May 15, 2011

I wanted to have unique tooltips on my points on a line chart generated using flot. I achieved this using the following code.

Data

My data series includes matching tooltips in the label field. These were in the same order as the data items.

{
    label: [
        ["21st Mar 2004<br/>London and Southern Counties (Championship Section),<br/>2nd <br/>John Clark"],
        ["16th Mar 2003<br/>London and Southern Counties (Championship Section),<br/>2nd <br/>Peter Parkes"],
        ["22nd Sep  2001<br/>National Championship of Great Britain (First Section Final),<br/>2nd <br/>B. Ellin"],
    ],
    points: { show: true, fillColor: "#919191" },
    color: '#919191',
    hoverable: true, 
    data: [
        [new Date("2004/03/21"), 2],
        [new Date("2003/03/16"), 2],
        [new Date("2001/09/22"), 2],
    ] 
  },

Note also the setting of hoverable to true.

Options

In the options, we also set the grid to be hoverable.

var lFlotOptions = { 
    grid: {
        hoverable: true
     }
 };

ShowTooltip Function

We next need a function to show the tooltip.

function showTooltip(x, y, contents) {
  $('<div id="flot_chart_tooltip">' + contents + '</div>').css( {
    top: y + 5,
    left: x + 5,
  }).appendTo("body").fadeIn(200);
}

We also need some CSS for this:

#flot_chart_tooltip{
    position: absolute;
    display: none;
    border: 1px solid #ddd;
    padding: 2px;
    background-color: #eee;
    opacity: 0.80;
}

Bind plothover event

Finally, we need to bind the plothover event.

$("#flot_chart").bind("plothover", function (event, pos, item) {
  if (item) {
    $("#flot_chart_tooltip").remove();
    showTooltip(item.pageX, item.pageY, item.series.label[item.dataIndex]);
  } else {
    $("#flot_chart_tooltip").remove();
  }
});

References

Tags: flot tooltip