0
votes

I am kind of new in chartJS framework, but this seems very odd to me. I have horizontal bar chart and 2 basic datasets in it. The thing is, that I am trying to make a button, that will change background color of dataset (in my case -> for dataset 1, but it doesn't really matter, it's just testing scenario). When I click on my button, it will change background color of bars in graph, but it will not change background color of my dataset legend.

Example: Dataset 1 has red background color. I click on my button and it will change background color of bars in graph on green(or some other color, it is not important). Legend of dataset 1 will stay red tho.

Here is my code

1

1 Answers

0
votes

First, for next time, you need to add a shortcode snippet of your code => Not Github with 2 long files & complex data - this is not a freelancer mission but Q :). Also in the future, you may delete this GitHub project and this Q will be meaningful.

. https://stackoverflow.com/help/how-to-ask

update()

It's pretty common to want to update charts after they've been created. When the chart data or options are changed, Chart.js will animate to the new data values and options. https://www.chartjs.org/docs/latest/developers/updates.html?h=update

Official Scriptable example (change colors & data by click): https://www.chartjs.org/samples/latest/scriptable/bar.html

or her (under the scriptable title): https://www.chartjs.org/samples/latest/

myHorizontalBar is your chart object so remove window. (Syntax error - check console errors).

window.myHorizontalBar.update(); /* wrong syntax remove "window." */

"hello world" example

/* data */
var data = {
  labels: ["Africa", "Asia", "Europe", "America"],
  datasets: [{
    /* data */
    label: "Data label",
    backgroundColor: ["red", "#8e5ea2","#3cba9f", '#1d49b8'],
    data: [5.0,6.7,7.5, 8.6, 3.3, 4.4, 4.5]
  }]
};

var options = {
  responsive: true,
  title: {
    text: 'Hello',
    display: true
  },
  scales: {
    xAxes: [{
      stacked: false,
      ticks: {

      },
    }],
    yAxes: [{
      stacked: true,
      ticks: {

      }
    }]
  }
};

var myChart = new Chart(document.getElementById("chart"), {
  type: 'bar',
  data: data,
  options: options
});

document.getElementById('submitChange').addEventListener('click', function() {
  myChart.data.datasets[0].backgroundColor[0] = "green";
  myChart.update();
});
<button id="submitChange">Change Africa color to Green</button>
<canvas id="chart"></canvas>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>