0

I'm trying to position a custom Chart.js tooltip on the middle of two bars. I made a research on the chart.js docs and different posts but didn't found any different approach than position it using the following snippet (I'm using jquery and doing a toggle class to hide/show the tooltip, please focus on the values I'm using to position the tooltip):

function setupTooltipPosition(config) {
  const { tooltipElement, tooltipModel } = config;
  const leftOffset = this._chart.canvas.offsetLeft;
  const topOffset = this._chart.canvas.offsetTop;

  tooltipElement.removeClass(tooltipSelectors.hide);
  tooltipElement.css('left', `${tooltipModel.caretX - leftOffset}px`);
  tooltipElement.css('top', `${tooltipModel.carteY - topOffset}px`);
}

Using this approach on this particular case I got this result:

[Tooltip positioned using default implementation]

I also tried using the x and y values of the tooltipModel , however , it doesn't add more sense of how to put the tooltip in the middle. If you tried to add a custom offset to put it on the middle , it works for just this case, but when you add more data it doesn't work. I can have at most 2 datasets, however, the user can add at most 10 data values that means 10 groups of bars.

The question is: There is a way to put the tooltip in the middle of the group of bars (or a single bar in case the user has just 1 dataset) using the values that Chart.js provide for tooltips? Or in other case, do you know any custom approach to have this tooltip centered?

Thanks!!

LxL
  • 1,878
  • 2
  • 20
  • 39

1 Answers1

0

You don't specify if 'middle' means on the x- and/or y-axis. But since you wrote:

...on the middle of two bars...

I assume you mean on the x-axis. In this case you need to set the options.tooltips.mode property to index. Below is a working example.

let myChart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: ['x', 'y', 'z'],
    datasets: [{
      label: '1993',
      data: [50, 30, 65],
      backgroundColor: '#503291'
    }, {
      label: '1994',
      data: [60, 15, 65],
      backgroundColor: '#1bbecd'
    }]
  },
  options: {
    tooltips: {
      mode: 'index'
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
      xAxes: [{
        barPercentage: 1
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.min.js"></script>
<canvas id="myChart"></canvas>

For future questions please provide a MCVE as that makes it much quicker and easier to help you.

timclutton
  • 12,682
  • 3
  • 33
  • 43