Chartjs-Have all label in Chartjs be at fixed positions

1👍

Put some time in and came up with a solution.

Charts gives us a .getPointsAtEvent() method, so using that, I was able to grab the data node at the hover location, get it’s label, and then display that label at a separate position.

$('.chart').each(function() {
  var chart = $(this).first().children('canvas')[0],
      label = $(chart).parents('.chart-container').find('.label-container').find('span');
  $(chart)
    .mousemove(function(evt) {
      var data_nodes = window.Chart[chart.id].getPointsAtEvent(evt);
      if (data_nodes.length > 0) {
        label.html(data_nodes[0].label);
        label.addClass('label-tooltip');
      } else {
        label.html('');
        label.removeClass('label-tooltip');
      }
    })
    .mouseleave(function() {
      label.html('');
      label.removeClass('label-tooltip');
    })
})

Grab each chart, iterate through them and find the canvas and the extra div that I’m using to store the tooltip (.label-container). Add the mousemove and mouseleave listeners to the chart. When the mouse moves, find the data nodes that it’s over, grab the first one (the very left one, even if multiple get selected) get the label from that node, then replace the label‘s html with that label. While the label is shown, I format it with CSS, so I also add a class label-tooltip to the label that styles it, otherwise it’s just hidden.

Result:
enter image description here

Leave a comment