Calculate the difference between two selected dataPoints - CanvasJS JavaScript Charts

Calculate the difference between two selected dataPoints - 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 -->
<div id="chartContainer" style="height: 360px; width: 100%;">
</div>
<div>  
  First x-value: <span id="showX1"></span><br/>
  Second x-value: <span id="showX2"></span><br/>
  Difference: <span id="showDifference"></span>
</div>

JavaScript

var clickCounter = 0;
var firstValue = 0, secondValue = 0;
var chart = new CanvasJS.Chart("chartContainer", {
  title: {
    text: "Select the dataPoints by clicking on it"
  },
  data: [{
  	click: selectOnClick,
    type: "line",
    markerSize: 0,
    selectedMarkerSize: 8, // Marker size by which selected dataPoints will be represented
    dataPoints: dataGenerator(100),
  }]
});

chart.render();


//----- Function for indicating selected dataPoints with marker size --------
function selectOnClick(e) {  
	clickCounter++;
	if( clickCounter % 2 != 0 ){
      firstValue = e.dataPoint.x;      
      for(var i = 0; i < e.dataSeries.dataPoints.length; i++){
        	e.dataSeries.dataPoints[i].markerSize = 0;
      }
      e.dataPoint.markerSize = e.dataSeries.selectedMarkerSize;
  }
  else {
      secondValue = e.dataPoint.x;      
      difference = calculateDiff(firstValue, secondValue);
      e.dataPoint.markerSize = e.dataSeries.selectedMarkerSize;
  }  
  e.chart.render();
  document.getElementById("showX1").innerHTML = firstValue;
  document.getElementById("showX2").innerHTML = secondValue;
  document.getElementById("showDifference").innerHTML = difference;
}

function calculateDiff(firstValue, secondValue){
    return Math.abs(firstValue - secondValue);
}

function dataGenerator(limit) {
  var y = 100;
  var points = [];
  for (var i = 0; i < limit; i += 1) {
    y += Math.round(Math.random() * 100 - 50);
    points.push({
      x: i - limit / 2,
      y: y
    });
  }
  return points;
}