Line chart tooltip - Javascript Chart.js

Javascript examples for Chart.js:Line Chart

Description

Line chart tooltip

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){//from ww  w .  ja  va 2 s  .c om
var fruits = ['Apples', 'Oranges', 'Tomotoes']
var datasets = fruits.map(function(a) {
  return {
    label: a,
    data: new Array(10).fill(0).map(Math.random),
    fill: false,
  }
})
function steppedHslColor(ratio, alpha) {
  return "hsla(" + 360 * ratio + ', 60%, 55%, ' + alpha + ')';
}
function colorizeDatasets(datasets) {
  for (var i = 0; i < datasets.length; i++) {
    var dataset = datasets[i]
    dataset.accentColor = steppedHslColor(i / datasets.length, 1)
    dataset.accentFadedColor = steppedHslColor(i / datasets.length, 0.2)
    dataset.backgroundColor = dataset.accentColor
    dataset.borderColor = dataset.accentColor
  }
  return datasets
}
colorizeDatasets(datasets)
var canvas = document.getElementById("myChart");
var ctx = canvas.getContext("2d");
var myChart = window.myChart = new Chart(ctx, {
  type: 'line',
  data: {
    //labels: labels,
    labels: new Array(10),
    datasets: datasets,
  },
  options: {
    title: {
      text: 'Fruit',
    },
    tooltips: {
      mode: 'index',
      intersect: false,
      itemSort: function (a, b, data) {
        return b.yLabel - a.yLabel // descending
      }
    },
    legend: {
      onHover: function(e, legendItem) {
        if (myChart.hoveringLegendIndex != legendItem.datasetIndex) {
          myChart.hoveringLegendIndex = legendItem.datasetIndex
          for (var i = 0; i < myChart.data.datasets.length; i++) {
            var dataset = myChart.data.datasets[i]
            if (i == legendItem.datasetIndex) {
              dataset.borderColor = dataset.accentColor
            } else {
              dataset.borderColor = dataset.accentFadedColor
            }
          }
          myChart.update()
        }
      }
    },
    hover: {
      mode: 'nearest',
      intersect: true,
    },
  }
});
myChart.hoveringLegendIndex = -1
myChart.canvas.addEventListener('mousemove', function(e) {
  if (myChart.hoveringLegendIndex >= 0) {
    if (e.layerX < myChart.legend.left || myChart.legend.right < e.layerX
      || e.layerY < myChart.legend.top || myChart.legend.bottom < e.layerY
    ) {
      myChart.hoveringLegendIndex = -1
      for (var i = 0; i < myChart.data.datasets.length; i++) {
        var dataset = myChart.data.datasets[i]
        dataset.borderColor = dataset.accentColor
      }
      myChart.update()
    }
  }
})
    }

      </script> 
   </head> 
   <body> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script> 
      <canvas id="myChart" width="300px" height="100px"></canvas>  
   </body>
</html>

Related Tutorials