get the label of a dataset in a stacked bar chart on clicking it? - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

get the label of a dataset in a stacked bar chart on clicking it?

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Stacked bar graph</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript">
    window.onload=function(){// ww w  .  j  a  v a 2 s.  c o m
      var dataPack1 = [1, 2, 3, 4, 5];
      var dataPack2 = [5, 4, 3, 2, 1];
      var dates = ["May 1", "May 2", "May 3", "May 4", "May 5"];
      var bar_ctx = document.getElementById('bar-chart');
      var bar_chart = new Chart(bar_ctx, {
        type: 'bar',
        data: {
          labels: dates,
          datasets: [{
            label: 'Bowser',
            data: dataPack1,
            backgroundColor: "rgba(55, 160, 225, 0.7)",
            hoverBackgroundColor: "rgba(55, 160, 225, 0.7)",
            hoverBorderWidth: 2,
            hoverBorderColor: 'lightgrey',
          onClick: function(evt, element) {
           console.log("Bowser");
              //var val = element.something such that val is assigned 'Bowser'
            }
          }, {
            label: 'Mario',
            data: dataPack2,
            backgroundColor: "rgba(225, 58, 55, 0.7)",
            hoverBackgroundColor: "rgba(225, 58, 55, 0.7)",
            hoverBorderWidth: 2,
            hoverBorderColor: 'lightgrey',
          onClick: function(evt, element) {
          console.log("Mario");
              //var val = element.something such that val is assigned 'Bowser'
            }
          }, ]
        },
        options: {
          animation: {
            duration: 10,
          },
          scales: {
            xAxes: [{
              stacked: true,
              gridLines: {
                display: false
              },
            }],
            yAxes: [{
              stacked: true
            }],
          }, // scales
          legend: {
            display: true
          }
        } // options
      });
    bar_ctx.onclick = function(evt){
        var activePoints = bar_chart.getElementAtEvent(evt);
        console.log(activePoints[0]._model.datasetLabel);
    };
    }

      </script> 
   </head> 
   <body>   
      <title>Testing</title> 
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.4/Chart.min.js"></script>   
      <canvas id="bar-chart" width="100" height="50"></canvas>    
   </body>
</html>

Related Tutorials