Chartjs and making an onClick action for a specific element?

๐Ÿ‘:0

One way we can do this, if we know some property of the point we want (such as x value in the example below), is to just use a conditional statement, like If, in the event handler function (i.e. in the function that says what happens when the chart is clicked on).

I feel like this is a better way to do this, but the approach does work.

Note: to see behavior click on left point, then click on right, and see difference

<!DOCTYPE html>
<head>
    <Title> Chart </Title>
    </head>
    <body>
        <p> Ex chart go</p>
        <div>
            <canvas id = "myChart"></canvas>
        </div>







        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
        <script>
            const ctx = document.getElementById(`myChart`);

            const scatterData = [{
                x:2,
                y:10
            },{
                x:4,
                y:10
            }]
            const toPlot = {
                // labels:xval,
                datasets: [{
                    // label: "Ex chart",
                    data: scatterData,
                    backgroundColor: "rgb(255,0,0)"
                }]
            };
            let myChart= new Chart(ctx, {
                type: `scatter`,
                data: toPlot,
                options: {
                    scales: {
                        x: {
                            min:1,
                            max:5,
                        }
                    }
                },
        });
        
        function clickHandler(evt) {
                const points = myChart.getElementsAtEventForMode(evt, 'nearest', { intersect: true }, true);

                if (points.length) {
                    const firstPoint = points[0];
                    var label = myChart.data.labels[firstPoint.index];
        var value = myChart.data.datasets[firstPoint.datasetIndex].data[firstPoint.index];
            if (1.5<value.x && value.x<2.2) {
        console.log("You clicked me!");
    }
                }
            }

    ctx.onclick = clickHandler;
        </script>
    </body>
    </html>

Leave a comment