So far, we haven't done a lot with the behavior of charts. One common behavior in charts is the tooltip
object, which can display useful information about a data point in the graph when a user hovers the mouse over that point. Tooltips are added by default to a graph, but it is useful to be able to extend this basic functionality.
To get started, perform the following instructions:
Create a function for our tooltip as follows:
var formatter = function () { var tooltipMessage = ''; tooltipMessage += 'X value: ' + this.x + '<br>'; for (var i=0; i < this.points.length; i++) { tooltipMessage += 'Y[' + i + '] value: ' + this.points[i].y+ '<br>' } return tooltipMessage; }
Define options for our chart as follows:
var options = { chart: { type: 'bar' }, title: { text: 'Creating custom tooltips' }, series: [{ name: 'Bar #1', data: [1,2,3,4] }, { name: 'Bar #2', data: [4,3,2,1] }] };
Assign this function to our options as
tooltip.formatter
, as shown in the following code:var options = { // ... tooltip: { formatter: formatter, borderColor: '#f00', backgroundColor: '#ccc', shared: true } };
Note
The formatter
function will render any string within the tooltip window. The this
keyword refers to the data point that we are hovering over, so we can access the x
and y
values of the current point via this.x
or this.y
.
We can also change the appearance of the tooltip via options such as changing the border with tooltip.borderColor
or the background with tooltip.backgroundColor
.
It is even possible to disable the tooltip entirely by setting tooltip.enabled
to false
.
More details on tooltip options can be found at http://api.highcharts.com/highcharts#tooltip or in the individual plot options for a chart at http://api.highcharts.com/highcharts#plotOptions.
By default, tooltips are not shared—every series displays only the data for its own tooltip. If you want to have all the data to be available from a single tooltip, you can set tooltip.shared
to true
. In this case, if we are using tooltip.formatter
, we need to change how we refer to our y
values, that is, instead of this.y
, we need to use this.points[i].y
(where i
is the series index). In fact, any value that we would normally access via this.<value>
needs to be accessed via this.points[i].<value>
when we have the shared
Boolean value set to true
. The one exception to this rule is this.x
, which is always common.
If we wanted, we could also make our tooltips look better by adding HTML to our formatter
function. The formatter
function supports the <b>
, <strong>
, <i>
, <em>
, and <br/>
tags, which gives us a bit more flexibility in how we design our tooltips. This is shown in the following code:
var options = { // ... tooltip: { formatter: function() { return 'The <b>value</b> at this point is <em>' + this.y +'</em>'; } } }