By Customizing Legend on-click actions
In Chart.js, you can use the legend.onClick callback function to customize the chart as well as the legend on click. This function is triggered when a legend item is clicked, allowing you to define custom behavior. Additionally, the e.stopPropagation() line prevents the default behavior of toggling the visibility of the corresponding dataset when the legend item is clicked. This allows you to have full control over the action triggered by the legend click.
Example: This example shows clicking on a legend item triggers the onClick function, which generates random data for both datasets and updates the chart.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" > < meta name = "viewport" content = "width=device-width, initial-scale=1.0" > < title >Dynamic Legend Action</ title > < script src = "https://cdn.jsdelivr.net/npm/chart.js" ></ script > </ head > < body > < div style = "width: 80%; margin: auto;" > < canvas id = "myChart" ></ canvas > </ div > < script > document.addEventListener('DOMContentLoaded', function () { let ctx = document.getElementById('myChart') .getContext('2d'); // Initial data let initialData = { labels: ['January', 'February', 'March', 'April', 'May'], datasets: [ { label: 'Sales', data: [50, 30, 40, 70, 90], backgroundColor: 'rgba(75, 192, 192, 0.2)', borderColor: 'rgba(75, 192, 192, 1)', borderWidth: 1 }, { label: 'Expenses', data: [20, 40, 10, 30, 50], backgroundColor: 'rgba(255, 99, 132, 0.2)', borderColor: 'rgba(255, 99, 132, 1)', borderWidth: 1 } ] }; let myChart = new Chart(ctx, { type: 'line', data: initialData, options: { legend: { display: true, position: 'top', onClick: function (e, legendItem) { // Generate random data for each dataset myChart.data.datasets.forEach(function (dataset) { dataset.data = Array.from({ length: initialData.labels.length }, () => Math.floor(Math.random() * 100)); }); // Update the chart myChart.update(); // Prevent the default legend behavior (toggle visibility) e.stopPropagation(); } } } }); }); </ script > </ body > </ html > |
Output:
How to Customize the Legend in Chart.js ?
In this article, we will learn how to customize the legend of a chart using the Chart JS CDN library. The chart legend displays data about the datasets that are appearing on the chart. This legend is customizable as per the users’ requirements to enhance the look and feel of the chart in conjunction with the chart layout.
CDN Link:
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
These are the following ways to customize the Legend:
Table of Content
- By Customizing Legend Title Configuration
- By Customizing Legend label Configuration
- By Customizing Legend on-click actions