How to display text information on hover in chart js?

👍:1

Simply add tooltips mode 'index' inside the chart options.

tooltips: {
  mode: 'index'
}

Please take a look at your amended code and see how it works.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ChartJS</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" integrity="sha512-/zs32ZEJh+/EO2N1b0PEdoA10JkdC3zJ8L5FTiQu82LR9S/rOQNfQN7U59U9BC12swNeRAz3HSzIL2vpp4fv3w==" crossorigin="anonymous">
</head>
<body>
    <canvas id="monGraph" width="400" height="100"></canvas>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js" integrity="sha512-s+xg36jbIujB2S2VKfpGmlC3T5V2TF3lY48DX7u2r9XzGzgPsa6wTpOQA7J9iffvdeBN0q9tKzRxVxw1JviZPg==" crossorigin="anonymous"></script>

    <script>
        let ctx = document.querySelector("#monGraph")
        let graph = new Chart(ctx, {
            type: "bar",
            data: {
                labels: ['Patrick', 'Josh', 'Sebastien', 'Oliver', 'Violette', 'Peter'],
                datasets: [{
                    label: 'Number of votes',
                    data: [12, 19, 3, 5, 2, 3],
                    // backgroundColor: ['red', 'blue', 'yellow', 'green', 'purple', 'orange']
                    backgroundColor: 'red'
                },
                {
                    label: 'Number of likes',
                    data: [14, 2, 5, 8, 7, 22],
                    // backgroundColor: ['red', 'lightblue', 'lightyellow', 'lightgreen', 'pink', 'gold']
                    backgroundColor: 'blue',                    
                }]
            },
            options: {
                title: {
                    display: true,
                    text: 'My nice Chart'
                },
                tooltips: {
                  mode: 'index'
                },
                legend: {
                    position: 'bottom'
                },
                scales: {
                    yAxes: [{
                        ticks: {
                            beginAtZero: true
                        }
                    }]
                }
            }
        })
    </script>
</body>
</html>

Leave a comment