[Chartjs]-Is it possible to use mouseenter and mouseleave event in chart js?

1👍

Your code is already designed to return to the original size on mouseout, but you have a subtle bug.

You need to define the segment variable outside the chart. With a saved reference to the segment, the mouseout event will fire and the onHover handler will return the pie to its original size.

Please see the attached example below:

let segment;
var ctx = document.getElementById('chartPie').getContext('2d');
var myChart = new Chart(ctx, {
  type: 'pie',
  data: {
    labels: ['Red', 'Blue', 'Green'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 20],
      backgroundColor: [
        'red',
        'blue',
        'green'
      ],
      datalabels: {
        color: '#000'
      }
    }]
  },
  options: {
    legend: {
      display: false
    },
    layout: {
      padding: 5
    },
    onHover: function(evt, elements) {
      if (elements && elements.length) {
        segment = elements[0];
        this.chart.update();
        selectedIndex = segment["_index"];
        segment._model.outerRadius += 5;
      } else {
        if (segment) {
          segment._model.outerRadius -= 5;
        }
        segment = null;
      }
    }
  }
});
.chart-pie {
  width: 400px;
  height: 400px;
  margin: auto;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.8.0"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>
<div class="container p-4">
  <div class="chart-pie position-relative">
    <canvas id="chartPie"></canvas>
  </div>
</div>

Leave a comment