Chartjs-ChartJS how to generate custom legend?

0๐Ÿ‘

โœ…

As i my dataset is load dynamically i had to add my legend logics in afterDatasetUpdate

So my code looks like this:

const chartRC = new Chart(document.getElementById("chartRC").getContext('2d'), {
    type: 'pie',
    data: {
        labels: [],
        datasets: [{
            fill: false,
            borderWidth: 2,
            pointBackgroundColor: '#0095ff',
            pointBorderColor: 'rgba(255,255,255,0)',
            pointHoverBackgroundColor: '#4683d3',
            data: [],
        }]
    },
    options: optionsRC,
    plugins: [{
        afterDatasetUpdate: function (chart, args, options) {
            if (chart.data.labels.length) {
                const chartId = chart.canvas.id
                const legendId = `${chartId}-legend`;
                const ul = document.createElement('ul');
                ul.setAttribute('data-chart-id', chart.id)
                chart.data.labels.forEach((label, i) => {
                    ul.innerHTML += `
                    <li>
                      <span style="background-color: ${chart.data.datasets[0].backgroundColor[i]}"></span>
                      ${label}
                    </li>
                `;
                })
                $(`#${legendId}`).delegate('li', 'click', legendClick);
                $(`#${legendId}`).delegate('li', 'mouseenter mouseleave', legendHover)
                return document.getElementById(legendId).appendChild(ul);
            }
            return;
        }
    }]
});

Leave a comment