ChartJS to click on bar and change it's background color - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

ChartJS to click on bar and change it's background color

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.bundle.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*www  .ja v a 2  s.c o m*/
var myChart = new Chart(document.getElementById("trendChart"), {
      type: 'bar',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
          label: '# of Votes',
          data: [12, 19, 3, 5, 2, 3],
          backgroundColor: 'rgb(124, 181, 236)'
        }]
      },
      options:{
         onClick: function(e){
        var element = this.getElementAtEvent(e);
        if(element.length > 0){
              element[0]._chart.controller.config.data.datasets[0]._meta[0].data[element[0]._index]._model.backgroundColor = "rgb(255,0,0)";
                myChart.render(0,true);
          }
        },
            scales: {
             yAxes: [{
               ticks: {
                 fontColor:'#fff'
               }
            }],
                  xAxes: [{
               ticks: {
                 fontColor:'#fff'
              }
             }],
         },
       legend:{
          display:false
        }
      }
    })
    }

      </script> 
   </head> 
   <body> 
      <div style="background:radial-gradient(ellipse at center, #6c7d84 0%, #2C434B 100%);"> 
         <canvas id="trendChart" width="500" height="300"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials