[Chartjs]-Interactive chart via ChartJS

3👍

  1. The method you should be using for a bar chart is getBarsAtEvent (getSegmentsAtEvent is for pie / doughnut and polar charts)

  2. getBarsAtEvent is a method on the bar chart object i.e. the one returned by the .Bar call.


So you need 2 minor changes as shown below

...
var actualBarChart = barChart.Bar(barChartData, barChartOptions);
...
...
     var activePoints = actualBarChart.getBarsAtEvent(evt);
...

0👍

I’m having an equivalent problem but with charts.js V2: even thought the code worked great on V1.1, not is completely useless.

This is the code I was using to trigger interaction between the legend and the chart:

    helpers.each(legendHolder.firstChild.childNodes, function(legendNode, index){
        helpers.addEvent(legendNode, 'mouseover', function(){
            var activeSegment = moduleDoughnut.segments[index];
            activeSegment.save();
            activeSegment.fillColor = activeSegment.highlightColor;
            moduleDoughnut.showTooltip([activeSegment]);
            activeSegment.restore();
        });
    });

As you can see, I had the “mouseover” event attached to every legend item. So when the item was hovered, the associated chart part got highlighted.

Now, I’ve been trying to get the same working using V2, but I just can’t find any way to trigger events on the chart.

Any ideas?


Update:

Evert Timberg at the GIT repository gave me this wonderfull and elegant solution which I enhanced by adding the mouseout event:

Chart.helpers.each(document.getElementById('legendContainer').firstChild.childNodes, function(legendNode, index) {
Chart.helpers.addEvent(legendNode, 'mouseover', function() {
    var activeSegment = window.myDoughnut.data.datasets[0].metaData[index];
    window.myDoughnut.tooltip.initialize();
    window.myDoughnut.tooltip._active = [activeSegment];
    window.myDoughnut.tooltip.update(true);
    window.myDoughnut.render(window.myDoughnut.options.hover.animationDuration, true);
});
Chart.helpers.addEvent(legendNode, 'mouseout', function() {
    window.myDoughnut.tooltip._active = [];
    window.myDoughnut.tooltip.update(true);
});
});

This is the event trigger code for the legend items.

Leave a comment