[Chartjs]-Get Chart js object from selector

3👍

You could directly use the graph object without assigning it to another variable ( considering graph is a global variable ) to add any sort of data from another function.

Here is a quick example of that …

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 graph variable is inside a function then, you’d have to make the variable global to use it from another function

10👍

Perhaps:

 var ctx = $('#graph');
 var graph = new Chart(ctx, {
     type: 'line',
     data: someData, 
 });
 ctx.data('graph', graph);

and later:

 var graph = $('#graph').data('graph');
 graph.data.labels.push(1)
 graph.data.datasets[0].data.push(10);
 graph.update();

 

// //

10👍

You can just do this:

var graph = Chart.getChart('graph')

Works in v3 – not sure when it was introduced.

2👍

//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();

Leave a comment