[Chartjs]-ChartJS click on bar and change it's background color

7๐Ÿ‘

โœ…

I found a pretty elegant solution By just modifying the backgroundColor saved within an array. Sadly a render() wasnโ€™t enough, therefor I need to do an update()..

Wish I could use ES6 by the way ๐Ÿ™‚

var backgroundColor = ['rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)',
    'rgb(124, 181, 236)'];

var a = 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: backgroundColor
    }]      
  },
  options:{
    onClick: function(e){
    var element = this.getElementAtEvent(e);
            for(var i=0;i<backgroundColor.length;i++){
        backgroundColor[i] = 'rgb(124, 181, 236)';
    }
         backgroundColor[element[0]._index] = 'red';
      this.update()
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
})

3๐Ÿ‘

If you spend some time playing with the console and your element, you see that if you log your element, you will have an array with only one object (the said element).

This object has itself several children, such as _index (what you used in your fiddle).
This is where you should start editing your element background.

If you go very deep inside the _chart child, you can finally edit the bar you want.

I updated your fiddle to see the result : here it is.


Note that the effect will disappear if you mouseleave out of the element.

2๐Ÿ‘

A little modification of the active property should give you the desired result.

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);

    // changes only the color of the active object
    this.active[0]._chart.config.data.datasets[0].backgroundColor = "red";

    if(element.length > 0){
            alert("Clicked on a bar with index: "+element[0]._index+". Now this bar should be marked as active.");
      }
    },
           scales: {
        yAxes: [{
            ticks: {
            fontColor:'#fff'
           }
        }],
                    xAxes: [{
            ticks: {
            fontColor:'#fff'
          }
         }],                    
     },
   legend:{
      display:false
    }
  }
});

Leave a comment