Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger hover programmatically in chartjs

I want to set the hover effect in ChartJs programmatically i wish to see both effects hoverBorderWidth, and hoverBorderColor. I know how to activate some tooltips, but I can't apply hover effects. For example, if I have chart and some links outside, I can trigger mouseover events to links. I want to have the hover effect in ChartJs, how can i do this?

Thanks for your answer.

like image 206
tetra master Avatar asked Dec 13 '18 14:12

tetra master


1 Answers

Chart.js listens for mousemove events and checks if a datapoint is at the x/y coordinates. If so, it triggers the 'hover' behaviour for that point.

Borrowing from the Chart.js tooltips test code, I wrote the snippet below to demonstrate accessing the correct properties and triggering an event.

let c = new Chart($('#chart'), {
  type: 'doughnut',
  data: {
    labels: ['a', 'b', 'c', 'd'],
    datasets: [{
      data: [1, 2, 4, 8],
      backgroundColor: ['red', 'blue', 'green', 'orange']
    }]
  },
  options: {
    maintainAspectRatio: false
  }
});
$('#a').on('click', function() { t(0); });
$('#b').on('click', function() { t(1); });
$('#c').on('click', function() { t(2); });
$('#d').on('click', function() { t(3); });

function t(idx) {
  var meta = c.getDatasetMeta(0),
    rect = c.canvas.getBoundingClientRect(),
    point = meta.data[idx].getCenterPoint(),
    evt = new MouseEvent('mousemove', {
      clientX: rect.left + point.x,
      clientY: rect.top + point.y
    }),
    node = c.canvas;
  node.dispatchEvent(evt);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<button id="a">Hover a</button>
<button id="b">Hover b</button>
<button id="c">Hover c</button>
<button id="d">Hover d</button>
<canvas id="chart"></canvas>
like image 68
timclutton Avatar answered Sep 18 '22 23:09

timclutton