kitchen800
kitchen800

Reputation: 227

Call ChartJS details in main Javascript file

I have a Charts JS chart. I am able to click on the chart and show some chart info that id like to see like so:

onClick: (evt, activeEls, chart) => {
    
    alert(chart.data.labels[activeEls[0].index]);

},

My chartJS script currently lives in the html file. However, when I try and move this into my main.js it doesn’t work (i.e the function doesn’t run). I cant seem to figure out why.

The set up is like so:

Main.JS:

function show_info() { 
alert(chart.data.labels[activeEls[0].index]);
}

And I have changed that chartJS section in my HTML file to:.

onClick: (evt, activeEls, chart) => {
    show_info();
    
},

How can I set it so that the function lives in my Main.js file?

Upvotes: 0

Views: 113

Answers (1)

Nechoj
Nechoj

Reputation: 1582

I think the variable chart is unknown in the scope of main.js. Therefore, you would need to provide the chart variable to show_info like so:

// main.js
function show_info(my_object) { 

alert(my_object.data.labels[activeEls[0].index]);
}

// other file
onClick: (evt, activeEls, chart) => {
    show_info(chart);
    
},

Upvotes: 1

Related Questions