ChartsJS Annotations Plugin - Can you create a tooltip to accompany an annotation?

1.9k views Asked by At

im trying to figure out how I can add a tooltip when I hover/mouseover the vertical line annotation I've drawn:

annotation: {
   annotations: [{
      "drawTime": "afterDatasetsDraw",
      "type": "line",
      "mode": "vertical",
      "scaleID": "x-axis-0",
      "value": "2020-04-01 12:20:27.709523",
      "borderWidth": 2,
      "borderColor": "red",
      "label": {
        "content": "Example Content",
        "enabled": true,
        "position": "top"
      },
      onMouseover: function(e) {
        console.log("I AM GETTING CALLED!");
      },
   },

Can anybody explain how this can be done?

2

There are 2 answers

0
Unmitigated On

You can use a label for the annotation whose display is changed when the mouse enters and leaves (see Events configuration).

annotation: {
    annotations: [{
        type: 'line',
        borderWidth: 2,
        xMin: someX,
        xMax: someX, // xMin = xMax for vertical line
        label: {
            display: false,
            backgroundColor: 'green',
            drawTime: 'afterDatasetsDraw',
            content: 'Some content for tooltip'
        },
        enter({ element }, event) {
            element.label.options.display = true;
            return true; // force update
        },
        leave({ element }, event) {
            element.label.options.display = false;
            return true;
        }
    }]
}

See the Label visibility example in the chartjs-plugin-annotation documentation.

0
XCS On

Not directly answering your question, but you can modify the chart and annotations in any way you prefer (in ChartJS v3) by accessing the context chart and element (docs)

I used this to change style of annotation on hover (in TypeScript):

enter: (context) => {
    const id = context.element.options.id!;
    ((context.chart.options.plugins!.annotation!.annotations as any)[id] as AnnotationOptions).borderColor = 'blue';
    context.chart.canvas.style.cursor = 'pointer';
    context.chart.update();
},
leave: (context) => {
    const id = context.element.options.id!;
    ((context.chart.options.plugins!.annotation!.annotations as any)[id] as AnnotationOptions).borderColor = 'rgb(255, 99, 132)';
    context.chart.canvas.style.cursor = 'default';
    context.chart.update();
},