Uncaught TypeError: Chart.register is not a function

276 Views Asked by At

I want to display datalables on top of eachbar(Datalabels are showing when i mouseover through the bar). I used chartdatalabels plugin to acheive this. But when i register the plugin using Chart.register(ChartDataLabels). Its throwing error and its not displaying the entire barchart.

Here is my code

<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>


var chartOptionsWeekly = {
        responsive: true,
        plugins: {
            datalabels: {
                anchor: 'end',
                align: 'end',
                labels: {
                    value: {
                        color: 'white'
                    }
                }
             }
        },
        legend: {
            position: "top",
            labels: {
                fontColor: "white"
            }
        },
        title: {
            display: false,
            text: "Daily Trend"
        },        
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true,                   
                    fontColor: 'white',
                    fontSize: 14,
                    stepSize: 20
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Attendance Percentage',
                    fontColor: 'white'
                }
            }],
            xAxes: [{
                ticks: {
                    beginAtZero: true,
                    fontColor: 'white',
                    fontSize: 14
                },
                scaleLabel: {
                    display: true,
                    labelString: 'Last 7 Days',
                    fontColor: 'white'
                }
            }]
        }
    }

Chart.register(ChartDataLabels)


window.onload = function () {        
        var ctxDaily = document.getElementById("barChartWeekly").getContext("2d");
        window.myBar = new Chart(ctxDaily, {
            type: "bar",
            plugins: [ChartDataLabels],
            data: barChartDataWeekly,            
            options: chartOptionsWeekly              
        });
        
    };

Any help would be appreciated. Thanks!

1

There are 1 best solutions below

0
On

Note that you're using an outdated version of Chart.js, the current version is 4.4.0.

Chart.register was introduced in Chart.js version 3, it replaced former Chart.plugins.register (see. 3.x Migration Guide -> Removed from Chart).

To solve your problem, you should use Chart.plugins.register or even better, use the most recent version of Chart.js.