[Chartjs]-Adding Chart.js line chart to Jinja2/Flask html page from JS file

4👍

First make sure the required JS is referenced in your template (or the template it extends).

Assuming you serve it from static/js folder:

<head>
    ...
    <script src='/static/js/Chart.bundle.min.js'></script>
    ...
</head>

Your script tag content looks mostly fine, just a little modification getting the context, and you appear to have a trailing }); that you need to remove:

<script>
    // get context
    var ctx = document.getElementById("line-chart").getContext("2d");

    ....

    // Create the chart
    var lineChart = new Chart(ctx, config);

    // REMOVE THIS FROM THE END OF YOUR SCRIPT
    //});
</script>

1👍

As bgse said in his answer you need to load library first. I suggest you use CDN as that way you don’t need to download ChartJS library.

Secondly, you’re writing some JS that may be executed before library is fetched to the page. So what would I add is:

<div class="card-body collapse in">
    <div class="card-block chartjs">
        <canvas id="line-chart" height="500"></canvas>
    </div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script>
    $(document).ready(function(){
        // Your JS code here
        // ...
    });
</script>

This way script code will execute when all JS is loaded.

Leave a comment