Chartjs-Display text on tooltip when hover over Doughnut chart in JS

0👍

You can use the tooltip callback for this:

tooltips: {
  callbacks: {
    label: (ctx, data) => (`Some text: ${data.datasets[ctx.datasetIndex].data[ctx.index]}`)
  }
},

Live sample:

const data = {
  //labels: ['xyz', 'abc'],
  datasets: [{
    label: 'Weekly Sales',
    data: [12, 20],
    backgroundColor: [
      'rgb(254, 214, 10)',
      'rgb(255, 90, 48)'
    ],
    borderColor: [
      "#ffffff",
    ],
    borderWidth: 1
  }]
};

var sum = 0;
var i;
for (i = 0; i < data.datasets[0].data.length; ++i) {
  sum += data.datasets[0].data[i];
}
console.log("sume", sum);
for (i = 0; i < data.datasets[0].data.length; ++i) {
  data.datasets[0].data[i] = Math.round((data.datasets[0].data[i] / sum) * 100);
}

// config 
const config = {
  type: 'doughnut',
  data,
  options: {
    tooltips: {
      callbacks: {
        label: (ctx, data) => (`Some text: ${data.datasets[ctx.datasetIndex].data[ctx.index]}`)
      }
    },
    plugins: {
      datalabels: {
        formatter: (value, ctx) => {
          let datasets = ctx.chart.data.datasets;
          if (datasets.indexOf(ctx.dataset) === datasets.length - 1) {
            //var sum = datasets[0].data.reduce((a, b) => a + b, 0);
            var percentage = Math.round((value / sum) * 100) + "%";
            return percentage;
          } else {
            return percentage;
          }
        },
        color: '#fff',
      }
    }
  }
};


// render init block
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);
$(document).ready(function() {
  $("#count1").text(data.datasets[0].data[0] + "%");
  $("#count2").text(data.datasets[0].data[1] + "%")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.7.0"></script>  -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/2.0.0/chartjs-plugin-datalabels.min.js"></script>

<canvas id="myChart"></canvas>

<div class="block-text">
  <div class="flex-chart">
    <div class="box-file"></div>
    <p class="spacing">abc</p>
    <p id="count1">20%</p>
  </div>

  <div class="flex-chart">
    <div class="box-url"></div>
    <p class="spacing">xyz</p>
    <p id="count2">30%</p>

  </div>
</div>

0👍

You are using Chart.js version 2.9.4 but the synytax is of version 3.x. If you the latest Chart.js version (3.8.2 as of right now), code works just fine.

Here’s your example: https://jsfiddle.net/zkx5acuv/5/

Leave a comment