charts - ChartsJS: Custom tooltip always displaying -
im using chartjs create graph on website.
im trying create custom tooltip. according documentation, should easy:
var mypiechart = new chart(ctx, { type: 'pie', data: data, options: { tooltips: { custom: function(tooltip) { // tooltip false if tooltip not visible or should hidden if (!tooltip) { return; } } } } }); my problem tooptip never false , because of custom tooltip displayed.
please see jsfiddle (line 42 never executed)
question: bug tooltip never false, or missing something?
the custom tooltip option used when want create/style own tooltip using htlm/css outside of scope of canvas (and not use built in tooltips @ all).
in order this, must define place outside of canvas contain tooltip (e.g. div) , use container within tooltips.custom function.
here example used custom tooltip display hovered pie chart section percentage in middle of chart. in example i'm generating tooltip inside div id "chartjs-tooltip". notice how interact div in tooltips.custom function position , change value.
also, correct way check if tooltip should hidden check it's opacity. tooltip object exist, when should not visible, opacity set 0.
chart.defaults.global.tooltips.custom = function(tooltip) { // tooltip element var tooltipel = document.getelementbyid('chartjs-tooltip'); // hide if no tooltip if (tooltip.opacity === 0) { tooltipel.style.opacity = 0; return; } // set text if (tooltip.body) { var total = 0; // value of datapoint var value = this._data.datasets[tooltip.datapoints[0].datasetindex].data[tooltip.datapoints[0].index].tolocalestring(); // calculate value of datapoints this._data.datasets[tooltip.datapoints[0].datasetindex].data.foreach(function(e) { total += e; }); // calculate percentage , set tooltip value tooltipel.innerhtml = '<h1>' + (value / total * 100) + '%</h1>'; } // calculate position of tooltip var centerx = (this._chartinstance.chartarea.left + this._chartinstance.chartarea.right) / 2; var centery = ((this._chartinstance.chartarea.top + this._chartinstance.chartarea.bottom) / 2); // display, position, , set styles font tooltipel.style.opacity = 1; tooltipel.style.left = centerx + 'px'; tooltipel.style.top = centery + 'px'; tooltipel.style.fontfamily = tooltip._fontfamily; tooltipel.style.fontsize = tooltip.fontsize; tooltipel.style.fontstyle = tooltip._fontstyle; tooltipel.style.padding = tooltip.ypadding + 'px ' + tooltip.xpadding + 'px'; }; here full codepen example.
i hope helps clear things up!
Comments
Post a Comment