Chartjs-How to have onclick/hover display associated value in ChartJS

0👍

Here’s a solution using tooltips (ignoring the Ajax from the OP):

var myChart
function refresh_graph() {
  var labels = ["Monday", "Tuesday", "Wednesday","Thursday","Friday","Saturday","Sunday"]
  var defaultData = [0.1,0.5,0.3,0.4,0.6,0.8,0.3]
  var more_info = ["Monday info", "Tuesday info", "Wednesday info","Thursday info","Friday info","Saturday info","Sunday info"]

  if(myChart){
    myChart.destroy();
  }

  var ctx = document.getElementById('myChart').getContext('2d');
  myChart = new Chart(ctx, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: "Price",
        data: defaultData,
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 2,
      }]
    },
    options: {
      responsive : true,
      tooltips : {
        callbacks : {
          title : function() {
            return 'More information:';
          },
          afterLabel : function(tooltipItem, data) {
            return 'Information: ' + more_info[tooltipItem.index];
          },
        }
      },
      elements: {
        line: {
          tension: 0
        }
      },
      legend: {
        display: false
      },
      scales: {
        yAxes: [{
          ticks: {
            suggestedMin: 0,
            suggestedMax: 1
          }
        }]
      },
      animation: {
        duration: 0
      },
      hover: {
        animationDuration: 0
      },
      responsiveAnimationDuration: 0
    }
  })
  setTimeout(refresh_graph, 50000);
}
setTimeout(refresh_graph, 0);

Full codepen with custom tooltip here: https://codepen.io/kh_one/pen/OJJPBpJ.

Leave a comment