How to highlight a single column and deselect previously highlighted column in Column chart of amCharts 4?
I am trying to change the colors of all the columns before highlighting the color of target column, but it is not working properly.
series.columns.template.events.on("hit", function(ev) {
ev.target.fill = am4core.color("red");
chart.invalidate();
});
You can use the active
state for that:
var activeState = series.columns.template.states.create("active");
activeState.properties.fill = am4core.color('red');
In your hit
event you can now set the columns to active. If you cache the last selected column, you can reset the active
state before setting the new column to active:
var currentActive;
series.columns.template.events.on("hit", function(ev) {
if (currentActive) {
currentActive.isActive = false;
}
currentActive = ev.target;
currentActive.isActive = true;
});
If you don't want to cache the last selection you can just deactivate a all columns before setting the new one:
series.columns.template.events.on("hit", function(ev) {
series.columns.values.forEach(c => c.isActive = false);
ev.target.isActive = true;
});
If you want to be able to unselect all columns again you can use this second method and extend it a bit:
series.columns.template.events.on("hit", function(ev) {
series.columns.values
.filter(c => c !== ev.target)
.forEach(c => c.isActive = false);
ev.target.isActive = !ev.target.isActive;
});
Here is a code pen showing the last behavior. You just have to replace the last bit to use the other options.