Get js chart object from selector
After creating a chart like this (with Chart.js , latest version):
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: someData,
});
I would like to get a Chart object in another function to add some data point to it:
var graph = ???
graph.data.labels.push(1)
graph.data.datasets[0].data.push(10);
How do I get the Chart object?
Thank you in advance!
+6
Joren inghelbrecht
source
to share
3 answers
You can use the object directly graph
without assigning it to another variable (given that it graph
is a global variable) to add any data from another function.
Here's a quick example of this ...
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May"],
datasets: [{
label: "Sales",
data: [1, 2, 3, 4, 5],
fill: false,
borderColor: '#07C',
}]
}
});
function addData() {
graph.data.labels.push('June')
graph.data.datasets[0].data.push(6);
graph.update();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
<button onclick="addData()">Add Data</button>
<canvas id="graph"></canvas>
in case: the variable graph
is inside a function, then you have to make the global variable use it from another function
+2
ษขสแดษดแด
source
to share
May be:
var ctx = $('#graph');
var graph = new Chart(ctx, {
type: 'line',
data: someData,
});
cxt.data('graph', graph);
and later:
var graph = $('#graph').data('graph');
graph.data.labels.push(1)
graph.data.datasets[0].data.push(10);
graph.update();
+3
Mario orlandi
source
to share
//get object
const chartJS: Chart = $("#myChart").data('chart');
//change something
chartJS.config.options.scales.yAxes[0].ticks.min = minVal <= 0 ? minVal : minVal -
//update
chartJS.update();
0
Maayan hope
source
to share