[Chartjs]-How to highlight single bar in bar chart using Chartjs

3👍

You can attach the logic to your onchange handler

document.getElementById("mySelect").onchange = highlightBar.bind(document.getElementById("mySelect"));

and if you want to call it programmatically (say, if you have an initial value set)

document.getElementById("mySelect").onchange();

Here’s the logic for highlighting the bars. Note that you need to consider the fact that the tooltip functionality also manipulates fill colors and stroke colors.

function highlightBar(s) {
    // this clears off any tooltip highlights
    myBarChart.update();
    myBarChart.activeElements = [];

    // reset any coloring because of selection
    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];

        // store the current values
        selectedBar.selected = {
            fillColor: selectedBar.fillColor,
            strokeColor: selectedBar.strokeColor
        }

        // now set the color
        selectedBar.fillColor = "red";
        selectedBar.strokeColor = "red";
    });

    myBarChart.update();
}

If however, you don’t have tooltips enabled, it becomes a whole lot simpler and you don’t need some of the above logic.


Working Fiddle – http://jsfiddle.net/39owabm0/198/

Leave a comment