JSFiddle - React, Tailwind, and code Playground
by klenwell
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<title>Chart with Dropdown</title>
</head>
<body>
<label for="datasetSelector">Select a Dataset:</label>
<select id="datasetSelector"></select>
<canvas id="myChart"></canvas>
<script>
const ctx = document.getElementById("myChart").getContext("2d");
let selectedDatasetIndex = null; // Track selected dataset
const bcolor = (c, n, selectedIndex) => {
//console.log(c.datasetIndex, n, selectedIndex)
if ( c.datasetIndex === selectedIndex ) {
return '#000000ff';
}
else {
return `hsl(${(n * 36) % 360}, 50%, 50%)`
}
}
// Generate 100 datasets with random data
const datasets = Array.from({ length: 100 }, (_, i) => ({
label: `Dataset ${i + 1}`,
data: Array.from({ length: 6 }, () => Math.floor(Math.random() * 50)),
borderColor: (ctx) => bcolor(ctx, i, selectedDatasetIndex),
borderWidth: (ctx) => (ctx.datasetIndex === selectedDatasetIndex ? 8 : 1), // Highlight selected dataset
backgroundColor: "transparent",
pointRadius: 0,
}));
const chart = new Chart(ctx, {
type: "line",
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
datasets: datasets,
},
options: {
responsive: true,
interaction: {
mode: "dataset",
intersect: false,
},
plugins: {
legend: {
display: false, // Hide legend for clarity
},
},
},
});
// Populate dropdown with dataset...