Blog>
Snippets

Creating a Custom Tooltip

Show how to create custom tooltip content that displays detailed information, such as percentages or category names, when hovering over different parts of a chart.
const customTooltip = (tooltipModel) => {
  // Tooltip Element
  let tooltipEl = document.getElementById('chartjs-tooltip');
  // Create element on first render
  if (!tooltipEl) {
    tooltipEl = document.createElement('div');
    tooltipEl.id = 'chartjs-tooltip';
    tooltipEl.innerHTML = '<table></table>';
    document.body.appendChild(tooltipEl);
  }
  // Hide if no tooltip
  if (tooltipModel.opacity === 0) {
    tooltipEl.style.opacity = 0;
    return;
  }
  // Set caret Position
  tooltipEl.classList.remove('above', 'below', 'no-transform');
  if (tooltipModel.yAlign) {
    tooltipEl.classList.add(tooltipModel.yAlign);
  } else {
    tooltipEl.classList.add('no-transform');
  }
};
This function creates a custom tooltip. It checks if a tooltip element exists, and if not, creates it. It then adjusts the tooltip's visibility and position based on the data.
const options = {
  tooltips: {
    enabled: false,
    custom: customTooltip,
    callbacks: {
      label: function(tooltipItem, data) {
        let label = data.labels[tooltipItem.index] || '';
        if (label) {
          label += ': ';
        }
        label += Math.round(tooltipItem.yLabel * 100) / 100;
        return label;
      }
    }
  }
};
This configures the chart to use the custom tooltip function we defined. Tooltips are disabled by default, and we provide a custom rendering function. We also define a callback to format the label displayed in the tooltip.