Sync ToolTip in StockChart when x values doesn't match
Sync ToolTip in StockChart when x values doesn't match
HTML
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://cdn.canvasjs.com/canvasjs.stock.min.js"></script>
<div id="chartContainer" style="height: 450px; width: 100%;"></div>
JavaScript
window.onload = function () {
var dataPoints1 = [], dataPoints2 = [], dataPoints3 = [];
var stockChart = new CanvasJS.StockChart("chartContainer",{
title:{
text:"LTC/USD"
},
theme: "light2",
charts: [{
toolTip:{
content: "{x}: {y}",
updated: showTooltip,
hidden: hideTooltip
},
data: [{
type: "line",
name: "Open Price",
dataPoints : dataPoints1
}]
}, {
toolTip:{
content: "{x}: {y}",
updated: showTooltip,
hidden: hideTooltip
},
data: [{
type: "line",
name: "Closing Price",
dataPoints : dataPoints2
}]
}
],
navigator: {
enabled:false
}
});
$.getJSON("https://canvasjs.com/data/docs/ltcusd2018.json", function(data) {
for(var i = 1; i < 11; i++){
dataPoints1.push({x: i * 2, y: Number(data[i].open)});
dataPoints2.push({x: i * 3, y: Number(data[i].close)});
}
stockChart.render();
});
function getNearestXValues(xVal, dps1) {
return [].concat(dps1).sort(function(a, b) {
var diffA = Math.abs(xVal - a.x);
var diffB = Math.abs(xVal - b.x);
return diffA - diffB; // sort a before b when the distance is smaller
})[0].x;
}
function showTooltip(e) {
for( var i = 0; i < stockChart.charts.length; i++){
if(stockChart.charts[i] != e.chart) {
stockChart.charts[i].toolTip.showAtX(getNearestXValues(e.entries[0].xValue, stockChart.charts[i].data[0].dataPoints));
}
}
}
function hideTooltip(e) {
for( var i = 0; i < stockChart.charts.length; i++){
if(stockChart.charts[i] != e.chart)
stockChart.charts[i].toolTip.hide();
}
}
}