chatwon
chatwon

Reputation: 90

How to change one point color on click in Highcharts

I'm trying to change the color of scatterplot points, one at a time. I have the code below which works, but I'm not sure how to change the color back when you click on a second point.

For example, I'd like it to work so if all the points are yellow by default and you click point A, point A alone turns black. Then when you click point B, point B turns black and point A turns back to yellow.

plotOptions: {
    series: {
        point: {
            events: {
                click: function() {
                    var thisPoint = this.options;
                    thisPoint.color = 'black';
                    this.update(thisPoint, true);
                }
            }
        }
    }
},

Upvotes: 3

Views: 616

Answers (1)

Halvor Holsten Strand
Halvor Holsten Strand

Reputation: 20536

You could store a variable containing the last clicked point, for example (in an outer scope):

let previousPoint;

And then in your click event:

plotOptions: {
    series: {
        point: {
            events: {
                click: function() {
                    // If we have a previous point, reset its color
                    if(previousPoint)
                        previousPoint.update({color: previousPoint.originalColor});
                    // Set this points color to black
                    this.update({color: 'black', originalColor: this.color});
                    // Make it our previous point
                    previousPoint = this;
                }
            }
        }
    }
}

See this JSFiddle demonstration of it in use.

If you don't want to clutter the Point with the extra variable (originalColor) you can also put a previousColor in your outer scope along with the previousPoint.

Upvotes: 1

Related Questions