[Chartjs]-How to highlight bar in ChartJS with onkeyup Input

1👍

Note that dataset.backgroundColor may be defined as a string or as an array of strings. Unfortunately this is not clearly reflected in the Chart.js documentation.

In order to have a specific bar highlighted, you need to define dataset.backgroundColor as an array of same colors, the color at the desired index however must be different.

This can be done with the following simple function.

function highlightMatchingBar() {
  var searchValue = document.getElementById('search').value.toUpperCase();
  chart.data.datasets[0].backgroundColor = labels.map(v => v.toUpperCase() == searchValue ? 'red' : 'green');
  chart.update();
}

Please take a look at below runnable code snippet, enter any valid animal name (case is irrelevant) and see how it works.

const labels = ['Cow', 'Horse', 'Dog', 'Cat', 'Bird', 'Fish', 'Sheep', 'Goat', 'Mouse', 'Rabbit', 'Bee', 'Rat', 'Pig', 'Fly'];
const chart = new Chart(document.getElementById('myChart'), {
  type: 'bar',
  data: {
    labels: labels,
    datasets: [{
      label: "My Dataset",
      data: labels.map(l => Math.floor(Math.random() * 1000) + 1),
      backgroundColor: 'green'
    }]
  },
  options: {
    legend: {
      display: false
    },
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});

function highlightMatchingBar() {
  var searchValue = document.getElementById('search').value.toUpperCase();
  chart.data.datasets[0].backgroundColor = labels.map(v => v.toUpperCase() == searchValue ? 'red' : 'green');
  chart.update();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<input id="search" type="text" id="myInput" onkeyup="highlightMatchingBar()" placeholder="Search...">
<canvas id="myChart" height="80"></canvas>

Leave a comment