javascript

Show vertical line on data point hover Chart.js

If you want to show a vertical line on the hover of a data point that is in your chart.js graphs, it’s not a straightforward process. Here's how you do it.

var ctx = document.getElementById('myChart');

var myChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: ['Label 1', 'Label 2', 'Label 3', 'Label 4'],
        datasets: [{
            label: 'Dataset label',
            data: [60, 40, 50, 35]
        }]
    },
    options: {
        interaction: {
            intersect: false,
            mode: 'index',
        }
    },
    plugins: [{
        afterDraw: chart => {
            if (chart.tooltip?._active?.length) {
                let x = chart.tooltip._active[0].element.x;
                let yAxis = chart.scales.y;
                let ctx = chart.ctx;
                ctx.save();
                ctx.beginPath();
                ctx.moveTo(x, yAxis.top);
                ctx.lineTo(x, yAxis.bottom);
                ctx.lineWidth = 1;
                ctx.strokeStyle = '#ff0000';
                ctx.stroke();
                ctx.restore();
            }
        }
    }],
});

To draw a vertical line on a data point, you first need to get the data point index of the particular data point that you want to highlight. You can do that by using the Chart.js plugin object as shown in the demo example below:

Basically, we have added two code blocks in our code when initializing the chart. 

In the plugin object, we have used method afterDraw and access chart plot points to fill vertical lines on the data points. The code that we are using for that is as below

plugins: [{
    afterDraw: chart => {
        if (chart.tooltip?._active?.length) {
            let x = chart.tooltip._active[0].element.x;
            let yAxis = chart.scales.y;
            let ctx = chart.ctx;
            ctx.save();
            ctx.beginPath();
            ctx.moveTo(x, yAxis.top);
            ctx.lineTo(x, yAxis.bottom);
            ctx.lineWidth = 1;
            ctx.strokeStyle = '#ff0000';
            ctx.stroke();
            ctx.restore();
        }
    }
}]

Apart from the above code we also need to define an interaction object and assign it to intersect and mode properties like the following code example.

options: {
    interaction: {
        intersect: false,
        mode: 'index',
    }
}
Was this helpful?