Legend showing corresponding Y-Values based on Crosshair Movement (Custom Legend) | CanvasJS JavaScript Charts

Legend showing corresponding Y-Values based on Crosshair Movement (Custom Legend) | CanvasJS JavaScript Charts

by canvasjs

HTML

<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<br/><!-- Just so that JSFiddle's Result label doesn't overlap the Chart -->
<!--Custom Legends-->
<div id="legends">
    <ul id="legendList">      
    </ul>
</div>
<div id="chartContainer" style="height: 360px; width: 100%;"></div>

CSS

li { 
  cursor: pointer;
  width: auto;
  display: inline;
  margin-left: 25px;
  min-width: 100px;
}

JavaScript

var chart = new CanvasJS.Chart("chartContainer", {    
  axisX: {
    crosshair: {
      enabled: true,
      snapToDataPoint: true,
      updated: function(e) {
        var dataPointIndex = getDataInfo(e.chart, e.value);
        for(var i = 0; i < e.chart.data.length; i++) {
          $("#" + i).text("-" + e.chart.data[i].name + ": " + e.chart.data[i].dataPoints[dataPointIndex].y);          
        }
      },
      hidden: function(e) {
        for(var i = 0; i < e.chart.data.length; i++) {
          $("#" + i).text("-" + e.chart.data[i].name);          
        }
      }
    }
  },
  data: [
    {
      type: "line",
      color: "red",
      name: "Red",
      dataPoints: [
        { x: 10, y: 21 },
        { x: 20, y: 25 },
        { x: 30, y: 20 },
        { x: 40, y: 25 },
        { x: 50, y: 27 },
        { x: 60, y: 28 },
        { x: 70, y: 28 },
        { x: 80, y: 24 },
        { x: 90, y: 26 }
      ]
    }, {
      type: "line",
      color: "green",
      name: "Green",
      dataPoints: [
        { x: 10, y: 31 },
        { x: 20, y: 35 },
        { x: 30, y: 30 },
        { x: 40, y: 35 },
        { x: 50, y: 35 },
        { x: 60, y: 38 },
        { x: 70, y: 38 },
        { x: 80, y: 34 },
        { x: 90, y: 44 }
      ]
    }, 
  ]

});

chart.render();

function getDataInfo(chart, xValue){
  for (var i=0; i < chart.data.length; i++) {
    for (var j=0; j < chart.data[i].dataPoints.length; j++) {
      if (chart.data[i].dataPoints[j].x === xValue) {
        return j;
      }
    }
  }
}


//Add custom-legends as list and attach click event to that
var legendListId = document.getElementById("legendList");
customLegends(chart,legendListId);

function customLegends(chart, legendListId){
  for(var i=0; i < chart.options.data.length; i++){	
    var li = document.createElement("li");
    li.style.color = chart.options.data[i].color;
    li.appendChild(document.createTextNode("-" + chart.options.data[i].name));
    legendListId.appendChild(li); 
   ...