Charts.js

Hi Guys, has anyone managed to get Charts.js working in Knack?

Sorry, nope, never tried :disappointed_relieved:

Hey Dagmar.

Yes I’ve implemented chart.js for a client of mine… What is the issue you’re facing?

1 Like

Hi Arjun, thanks for the response.

The Charts.js documentation is very clear, but it only explains how to implement charts directly in a webpage. I am struggling, however, with taking that to the Knack environment where the Javascript does not form part of the initial page, but is coded in a separate environment.

Would it be possible to show me an example? Any help would be greatly appreciated.

Of course. It’s pretty simple actually.

You first need to lazyload the chart.js script:

LazyLoad.js(['https://cdn.jsdelivr.net/npm/chart.js@2.7.1/dist/Chart.min.js', 'https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels@0.2.0'], function () {
    //console.log('All my files have completed loading!');
});

Then you need to add a div element where you’d like to render the chart and use the new Chart() function to render it with the data you’d like:

$(document).on('knack-view-render.view_xx', function(event, view, records) {
    $("#view_xx > section > div.kn-details-column.first.column.is-horizontal > div > div > div > div.kn-detail.field_yy").before("<canvas id=\"myChart\"></canvas>");
    new Chart(document.getElementById("myChart"), {
        // Your chart preferences and data
    });
});

Let me know if this makes sense or if you run into any issues implementing this.