Chartjs-Is it possible to add a click event in chart.js that directs you to a url?

1👍

It can be done through an onClick event handler, which indeed is poorly documented.

const labels = ["January", "February", "March", "April", "May", "June", "July"];
const data = [65, 59, 80, 81, 56, 55, 40];
const chart = new Chart(document.getElementById('myChart').getContext('2d'), {
    type: "bar",
    data: {
        labels: labels,
        datasets: [{
            label: "My First Dataset",
            data: data,
            fill: false,
            backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(255, 159, 64, 0.2)", "rgba(255, 205, 86, 0.2)", "rgba(75, 192, 192, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(153, 102, 255, 0.2)", "rgba(201, 203, 207, 0.2)"],
            borderColor: ["rgb(255, 99, 132)", "rgb(255, 159, 64)", "rgb(255, 205, 86)", "rgb(75, 192, 192)", "rgb(54, 162, 235)", "rgb(153, 102, 255)", "rgb(201, 203, 207)"],
            borderWidth: 1
        }]
    },
    options: {
       onClick: event => {
          const idx = chart.getElementAtEvent(event)[0]._index;
          const url = "https://www.acme.com/details?month=" + labels[idx] + "&value=" + data[idx];
          window.open(url, "_blank");
       }
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

Note that opening a new window through above code snipped is blocked
because the request is made in a sandboxed frame whose ‘allow-popups’
permission is not set.

Leave a comment