Highlight single bar in bar chart using Chartjs - Javascript Chart.js

Javascript examples for Chart.js:Bar Chart

Description

Highlight single bar in bar chart using Chartjs

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>line chart with ChartJS</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.0/Chart.min.js"></script> 
      <script type="text/javascript">
    window.onload=function(){/*  w w  w  . j  a  v a2  s .co  m*/
var data = {
    labels: ["January", "February", "March", "April", "May", "June", "July"],
    datasets: [
        {
            label: "My First dataset",
            fillColor: "rgba(220,220,220,0.5)",
            strokeColor: "rgba(220,220,220,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(220,220,220,1)",
            data: [65, 59, 80, 81, 56, 55, 40]
        },
    ]
};
var ctx = document.getElementById('canvas').getContext('2d');
var myBarChart = new Chart(ctx).Bar(data);
function highlightBar(s) {
    myBarChart.update();
    myBarChart.activeElements = [];
    myBarChart.datasets.forEach(function (dataset) {
        dataset.bars.forEach(function (bar) {
            if (bar.selected) {
                bar.fillColor = bar.selected.fillColor;
                bar.strokeColor = bar.selected.strokeColor;
                delete bar.selected;
            }
        })
    });
    var index = myBarChart.scale.xLabels.indexOf(this.value);
    myBarChart.datasets.forEach(function (dataset) {
        var selectedBar = dataset.bars[index];
        selectedBar.selected = {
            fillColor: selectedBar.fillColor,
            strokeColor: selectedBar.strokeColor
        }
        selectedBar.fillColor = "red";
        selectedBar.strokeColor = "red";
    });
    myBarChart.update();
}
document.getElementById("mySelect").onchange = highlightBar.bind(document.getElementById("mySelect"));
document.getElementById("mySelect").onchange();
    }

      </script> 
   </head> 
   <body> 
      <select id="mySelect"> 
         <option>January</option> 
         <option>February</option> 
         <option>March</option> 
         <option>April</option> 
         <option>May</option> 
         <option>June</option> 
         <option>July</option> 
      </select> 
      <br> 
      <canvas id="canvas" height="300" width="600"></canvas>  
   </body>
</html>

Related Tutorials