Home > database >  Dispaly text on tooltip when hover over Doughnut chart in JS
Dispaly text on tooltip when hover over Doughnut chart in JS

Time:08-02

Here is the code. I am new in Js. I want to display text with data on tooltip when we hover on the doughnut without active the labels mentioned in datasets

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: {
    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/[email protected]"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></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 >
             <div > <div ></div><p >abc</p>
             <p id = "count1">20%</p></div>

             <div > <div ></div><p >xyz</p> 
             <p id = "count2">30%</p>

         </div>
         </div>

As you can see in the code. I have commented the label heading (//labels: ['xyz', 'abc']) without uncommenting this line, I just want text in replace of undefined on tooltip when I'll hover on Doughnut Chart in JS.

CodePudding user response:

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/[email protected]"></script>
<!--  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></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 >
  <div >
    <div ></div>
    <p >abc</p>
    <p id="count1">20%</p>
  </div>

  <div >
    <div ></div>
    <p >xyz</p>
    <p id="count2">30%</p>

  </div>
</div>

CodePudding user response:

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/

  • Related