2

This question might seem easy, but I don't know how to solve it.

I have this codepen. What I want is to run a script using the actual title. Example if section with "S: 7" is hovered, I want to console.log() the "S: 7". Can you please help ?

MJH
  • 2,301
  • 7
  • 18
  • 20
dmx
  • 1,862
  • 3
  • 26
  • 48

1 Answers1

1

I'm not familiar with chart.js, so this codepen is somewhat of a hack, but for the most part it appears to work. It uses the code in @drinor's answer to this question.

One potential issue is that if you hover over a particular slice, then move the mouse off of the pie, then again hover over that same slice, nothing is written to the console. If you do want console output in this case, it seems you could do so by adding a mouseout event that sets currentIndex = -1.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script>
        <style type="text/css">
            .container {
              width: 80%;
              margin: 15px auto;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <h2>Chart.js — Pie Chart Demo (apples)</h2>
            <div>
                <canvas id="myChart"></canvas>
            </div>
        </div>

        <script type="text/javascript">

            var currentIndex = -1;

            Chart.defaults.global.hover.onHover = function(x) {
                if(x[0]) {
                    var index = x[0]._index;

                    if (index !== currentIndex) {
                        currentIndex = index;
                        console.log(x[0]._model.label + ': ' + x[0]._chart.config.data.datasets[0].data[index]);
                    }
                }
            };

            var ctx = document.getElementById("myChart").getContext('2d');
            var myChart = new Chart(ctx, {
              type: 'pie',
              data: {
                labels: ["M", "T", "W", "T", "F", "S", "S"],
                datasets: [{
                  backgroundColor: [
                    "#2ecc71",
                    "#3498db",
                    "#95a5a6",
                    "#9b59b6",
                    "#f1c40f",
                    "#e74c3c",
                    "#34495e"
                  ],
                  data: [12, 19, 3, 17, 28, 24, 7]
                }]
              }
            });
        </script>
    </body>
</html>
Community
  • 1
  • 1
MJH
  • 2,301
  • 7
  • 18
  • 20