My chart is defined as
var myChart = new CanvasJS.Chart("myChartContainer", {
animationEnabled: true,
axisY :{
includeZero: false,
gridColor: "rgba(140, 140, 140, 1)"
},
toolTip: {
shared: true,
content: false
},
legend: {
fontSize: 13
},
data: myChartData.json
});
And I need to access the chart's instance via its DOM element (I don't want to make myChart a global variable. I've tried retrieving the chart's instance using these two methods
var charr = $('#myChartContainer').CanvasJS()
var charr = $('#myChartContainer').CanvasJSChart()
But none of them work. The first throws jquery-3.4.1.min.js:2 Uncaught TypeError: $(...).CanvasJS is not a function, and the second just returns an undefined object. I am using the jQuery plugin of CanvasJS.
What am I missing? How can I retrieve the chart's instance?
FYI, I have seen this answer, but it didn't help.
Based on the code sample that you have shared, you seem to be using jQuery plugin of CanvasJS but creating chart JavaScript way. As per CanvasJS jQuery documentation, you can create chart as $("#myChartContainer").CanvasJSChart(chartOptions); & then you can get the reference to the chart as $("#myChartContainer").CanvasJSChart();. Working example shown below.
var options = {
title: {
text: "CanvasJS jQuery Chart"
},
data: [{
type: "line",
dataPoints: [
{ x: 1, y: 63 },
{ x: 2, y: 69 },
{ x: 3, y: 65 },
{ x: 4, y: 70 },
{ x: 5, y: 71 },
{ x: 6, y: 65 },
{ x: 7, y: 73 },
{ x: 8, y: 96 },
{ x: 9, y: 84 },
{ x: 10, y: 85 },
{ x: 11, y: 86 },
{ x: 12, y: 94 },
{ x: 13, y: 97 },
{ x: 14, y: 86 },
{ x: 15, y: 89 }
]
}]
};
$("#chartContainer").CanvasJSChart(options);
var chart = $("#chartContainer").CanvasJSChart(); //Get reference to the chart instance
/*chart.options.title.text = "New Title";
chart.render();*/
<script src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://canvasjs.com/assets/script/jquery.canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>