[Chartjs]-How to add custom tooltips to only one label in Chart.js?

1👍

A bit hacky solution but it seems to be working. StackBlitz demo.

Looking at the other answers for similar questions (e.g. How to diable a tooltip for a specific dataset) I could not find the way to disable the tooltip dynamically and use the custom tooltip instead.

The main idea is to leave the default tooltip enabled but change it to disabled in the custom tooltip function.

  options: {
    responsive: true,
    tooltips: {
      enabled: true,
      custom: function (tooltipModel) {
        if (isCustomTooltipMode(tooltipModel, 'OpenCoesione')) {
          setDefaultTooltipEnabled(this, false);
        } else {
          setDefaultTooltipEnabled(this, true);
          return;
        }

        var tooltipEl = document.getElementById('chartjs-tooltip');
        // Hide if no tooltip
        if (tooltipModel.opacity === 0 && tooltipEl) {
          tooltipEl.style.opacity = 0;
          return;
        }

        // Create element on first render
        createCustomTooltip(this, tooltipEl, tooltipModel);
      }
    }
  }
function isCustomTooltipMode(tooltipModel, labelName) {
  return tooltipModel.dataPoints == null || tooltipModel.dataPoints[0].xLabel === labelName;
}

/*
  the hacky way (could not find the better one)
*/
function setDefaultTooltipEnabled(chart, enabled) {
  chart._chart.tooltip._options.enabled = enabled;
}

In the createCustomTooltip function you can define how the tooltip for ‘OpenCoesione’ should look.

Chart.js docs that I’ve found useful:
External custom tooltips, Tooltip Model, Tooltip Item

Leave a comment