Open and close Chart.js tooltip - Javascript Chart.js

Javascript examples for Chart.js:Chart Tooltip

Description

Open and close Chart.js tooltip

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://npmcdn.com/chart.js/dist/Chart.js"></script> 
      <script type="text/javascript">
    window.onload=function(){//w  w w  .  j a v a 2s  . c om
function openTip(oChart,datasetIndex,pointIndex){
   if(oChart.tooltip._active == undefined)
      oChart.tooltip._active = []
   var activeElements = oChart.tooltip._active;
   var requestedElem = oChart.getDatasetMeta(datasetIndex).data[pointIndex];
   for(var i = 0; i < activeElements.length; i++) {
       if(requestedElem._index == activeElements[i]._index)
          return;
   }
   activeElements.push(requestedElem);
   oChart.tooltip._active = activeElements;
   oChart.tooltip.update(true);
   oChart.draw();
}
function closeTip(oChart,datasetIndex,pointIndex){
   var activeElements = oChart.tooltip._active;
   if(activeElements == undefined || activeElements.length == 0)
     return;
   var requestedElem = oChart.getDatasetMeta(datasetIndex).data[pointIndex];
   for(var i = 0; i < activeElements.length; i++) {
       if(requestedElem._index == activeElements[i]._index)  {
          activeElements.splice(i, 1);
          break;
       }
   }
   oChart.tooltip._active = activeElements;
   oChart.tooltip.update(true);
   oChart.draw();
}
var barChartData = {
  labels: ["January", "February", "March", "April", "May", "June", "July"],
  datasets: [{
    label: 'Dataset 1',
    backgroundColor: 'rgb(255, 99, 132)',
    data: [10, 20, 30, 40, 50, 60, 70]
  }]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.oChart = new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: {
    tooltips: {
      mode: 'label'
    },
    responsive: true
  }
});
window.openTip = openTip;
window.closeTip = closeTip;
    }

      </script> 
   </head> 
   <body> 
      <canvas id="canvas"></canvas> 
      <button onclick="openTip(oChart,0,2)"> Open March </button> 
      <button onclick="closeTip(oChart,0,2)"> Close March </button>  
   </body>
</html>

Related Tutorials