chart.js - link to other page when click on specific section in chart ( With Bar Chart )

Viewed 22

i've tried using method for link specific section using static data and it work , but when I use dynamic data and try to use bar chart (even I have found a solution here using pie chart) but I don't succeed and mess up the rest of the page.

Sorry if this is a bit fuzzy, i'm kind of new to this.

here's my code

var ctxUO = document.getElementById("canvas").getContext('2d');

var myChart4 = new Chart(ctxUO, {
    type: 'bar',
    data: {
        labels: {{newlabels2|safe}},
        datasets: [{
            label: '1',
            data: {{data1|safe}},
            backgroundColor: [
                'MediumBlue',
                
            ]
        },{
            label: '2',
            data: {{data2|safe}},
            backgroundColor: [
                'DarkOrange',
                
            ]
        }
    ]},

    options: {

        indexAxis: 'y',
        scales: {
            y: {
                beginAtZero: true
            }
        }
    },

});


function clickHandler(click){
    var points = myChart4.getElementsAtEventForMode(click, 'nearest', { intersect: true}, true);
    if (!points.length) return; // return if not clicked on slice
    var label = points[0]._model.label; // use the first one
    console.log(points)
    console.log(label)
        switch (label) {
        // add case for each label/slice
        case '1':
            alert('Bar Clicked');
            window.open('www.example.com/foo');
            break;
        case '2':
            alert('Bar Clicked ');
            window.open('www.example.com/bar');
            break;
        // add rests ...
    }
}

ctxUO.onclick = clickHandler;

I would be very grateful if anyone knows where the error in my code or maybe has a better solution regarding link clickable bar charts

0 Answers
Related