David G
David G

Reputation: 337

Chart.js chart onclick disables legend onclick

I have just added a chart onclick function to a bar chart which allows me to take an action depending on which bar is clicked - works great - but (you knew there was a but) it disables the normal legend onclick functionailty. How can I have both onclick functionalities?

I am guessing it might be something like calling the legend onclick callback function from the chart onclick function but the details are beyond my current knowledge.

I got as far as this, but not sure what the parameters should be for the call to the default handler.

var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;

function YrChartClick(event, YCarray)
  {
    if (typeof YCarray[0] === "undefined")  //click not on a bar, might be legend
    defaultLegendClickHandler(event, 1);  // parameters?? correct function?
else
{
//clicked on a bar - this works
    $('#month').val(YCarray[0]._index+1);  
    MonChange();
}
}

Using the latest version of chart.js 2.7.1

Upvotes: 2

Views: 2781

Answers (1)

soran_glekovec
soran_glekovec

Reputation: 103

Try like that:

var legendClick = Chart.defaults.global.legend.onClick;
Chart.defaults.global.legend.onClick = function(e, legendItem) {
    console.log(legendItem);
    legendClick.call(this, e, legendItem);
};

legendItem contains the index of the bar that was clicked.

legendClick.call(this, e, legendItem) performs the default click handler.

Upvotes: 4

Related Questions