[Chartjs]-Chart.js – doughnut show active segment tooltip (on click of external button)

3👍

You can use the following function to display corresponding tooltip, when clicked on an external button :

function showTooltip(chart, index) {
   var segment = chart.getDatasetMeta(0).data[index];
   chart.tooltip._active = [segment];
   chart.tooltip.update();
   chart.draw();
}

When calling the function, pass chart-instance and button-index as the first and second argument respectively.

BONUS :

To initially show the tooltip of segment-1, add the following config in your chart options :

animation: {
   onComplete: function() {
      if (!isChartRendered) {
         showTooltip(myChart, 0);
         isChartRendered = true;
      }
   }
}

* declare a variable named isChartRendered in global-scope and set it to false

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ ⧩

var isChartRendered = false;
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
   type: 'doughnut',
   data: {
      labels: ['Segment 1', 'Segment 2', 'Segment 3'],
      datasets: [{
         data: [10, 10, 10]
      }]
   },
   options: {
      events: ['click'],
      cutoutPercentage: 70,
      legend: {
         display: false
      },
      tooltips: {
         displayColors: false
      },
      onClick: function(evt, elements) {},
      // BONUS: show segment 1 tooltip initially
      animation: {
         onComplete: function() {
            if (!isChartRendered) {
               showTooltip(myChart, 0);
               isChartRendered = true;
            }
         }
      }
   }
});

$(document).on('click', 'button', function() {
   var $this = $(this),
       index = $this.index();
   showTooltip(myChart, index);
});

function showTooltip(chart, index) {
   var segment = chart.getDatasetMeta(0).data[index];
   chart.tooltip._active = [segment];
   chart.tooltip.update();
   chart.draw();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:400px;height:400px;">
   <canvas id="myChart"></canvas>
</div>

<div style="margin-top:50px;">
   <button>Trigger Segment 1 Click</button>
   <button>Trigger Segment 2 Click</button>
   <button>Trigger Segment 3 Click</button>
</div>

0👍

For Chart.js 3 the GRUNT`s solution needs some modifications:

chart.tooltip.setActiveElements([{datasetIndex: 0, index: index}]);
chart.tooltip.update();
chart.render();

If you want to change also the segment style:

const activeSegment = chart.getDatasetMeta(0).data[index];
chart.updateHoverStyle([{element: activeSegment, datasetIndex: 0}], null, true);

Leave a comment