1

In one html page, I have a select menu (a,b,c,d) and a bar chart (bar a,b,c,d). What I want to do is to highlight the corresponding bar in the bar chart that is selected in the select menu.

Steven Luo
  • 2,350
  • 3
  • 18
  • 35
  • By highlight do you mean make it a different color than the rest? If so you could do something like this: http://stackoverflow.com/questions/25594478/different-color-for-each-bar-in-a-bar-chart-chartjs It depends on how you're generating your chart, if you shared some code that would be helpful. But I would match the positions of the labels in the chart with the menu and then onclick, find what position the menu item was when it was clicked, and then do a fill color on the bar chart at the same position. – Joshua Terrill Aug 22 '15 at 09:09

1 Answers1

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/

Kunal Khivensara
  • 1,619
  • 14
  • 21
potatopeelings
  • 40,709
  • 7
  • 95
  • 119
  • Please update the link to the Chartjs library (404 on jsfiddle). Guess must be such [link](https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.0/Chart.min.js) – Andron Oct 16 '18 at 14:16