[Chartjs]-Is there a way to apply css on chart.js V3.7.0 tooltip without it being custom or external?

3👍

You can’t use CSS since its not HTML styling because its drawn on the canvas.

What you can do is provide a custom positioner for the tooltip to chart.js.
In the Sample below you can see how to do it. Increading the yOffset variable I declared on top will move the tooltip more above the point and increasing the xOffset variable I declared on top it will move the tooltip more to the right:

const yOffset = 10;
const xOffset = 00;

Chart.Tooltip.positioners.custom = function(items) {
  const pos = Chart.Tooltip.positioners.average(items);

  // Happens when nothing is found
  if (pos === false) {
    return false;
  }

  const chart = this.chart;

  return {
    x: pos.x + xOffset,
    y: pos.y - yOffset,
    yAlign: 'bottom',
  };
}

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderWidth: 1
      }
    ]
  },
  options: {
    plugins: {
      tooltip: {
        caretPadding: 3,
        caretSize: 0,
        displayColors: false,
        backgroundColor: 'rgba(45,132,180,0.8)',
        bodyFontColor: 'rgb(255,255,255)',
        callbacks: {
          title: () => {
            return
          },
          label: (ttItem) => (`${ttItem.parsed.y} ppm`),
          afterBody: (ttItems) => (ttItems[0].label)
        },
        position: 'custom'
      }
    }
  }
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.js"></script>
</body>

Leave a comment