1
votes

I'm using Chart.js to display some data using a bar chart. My question is whether there is a way to extract the text of the tooltip and show it on a different div, so whenever I hover the bar chart I get the label and the value hovered in another place of the page.

I managed to alert the label or the value using the alert(label) function. but when I use the $('#mydiv').text(label) function, It does not work. Here is my code :

<canvas id="widgetChart4"></canvas>
<id id="myDiv"></id>


<script>
var ctx = document.getElementById( "widgetChart4" );
ctx.height=50;
ctx.width=250;
var myChart = new Chart( ctx, {
    type: 'bar',
    data: 
    {
    labels: [ "January", "February", "March", "April", "May", "June", 
       "July" ],
    datasets: [
            {
                label: false,
                data: [ 16, 32, 18, 26, 42, 33, 44 ]
             }
              ]
    },
    options: 
    {
        responsive: true,
        tooltips: 
        {
           callbacks: 
         {
           label: function(tooltipItem, data) {
           //this is working
           alert( data['datasets'][0]['data'][tooltipItem['index']]);
           //this is not working
           $("#myDiv").text(data['datasets'][0]['data'] 
           [tooltipItem['index']]);
           return data['datasets'][0]['data'][tooltipItem['index']];
           },
         }
        }

    }
    });
</script>
1

1 Answers

1
votes

I managed to alert the label or the value using the alert(label) function. but when I use the $('#mydiv').text(label) function, It does not work.

I ran your code and it works perfectly so one possible reason why it's not working on your side is that you didn't import jQuery in your code.

var ctx = document.getElementById("widgetChart4");
ctx.height = 50;
ctx.width = 250;
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["January", "February", "March", "April", "May", "June",
      "July"
    ],
    datasets: [{
      label: false,
      data: [16, 32, 18, 26, 42, 33, 44]
    }]
  },
  options: {
    responsive: true,
    tooltips: {
      callbacks: {
        label: function(tooltipItem, data) {
          $('#myDiv').html(data['datasets'][0]['data']
            [tooltipItem['index']]);
          return data['datasets'][0]['data'][tooltipItem['index']];
        },
      }
    }

  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<canvas id="widgetChart4"></canvas>
<div id="myDiv"></div>