Reputation: 105
I am working with a scatterplot in d3 and each dot on the graph represents a paper.
All dots are blue on the graph but on click I want that selected paper to change color eg (yellow). But when another dot is clicked I want that first dot to go back to blue and the newly selected dot to turn yellow. How would I achieve this? I have a function called clickHandler which is called when the circles are created at the on click attribute.
Here is a similar question d3 javascript alternate colors on click
But instead of the circle turning back to the original color on the second click of that circle I want it to turn back on a click of another circle.
The following code is from the question linked above, I was wondering would I be on the right track thinking this is the method I should be following for what I want?:
function clickHandler (d, i) {
var toggleColor = (function() {
var currentColor = "blue";
return function() {
currentColor = currentColor == "blue" ? "yellow" : "blue";
d3.select(this).style("fill", currentColor)
.style("stroke", "black");
}
})
}
Any help is greatly appreciated! Thanks in advance!
Upvotes: 1
Views: 2905
Reputation: 108557
This can be as simple as:
function clickHandler (d, i) {
// reset all circle to blue
d3.selectAll('circle') //<-- or slap a class name on your circles and use that
.style('fill', 'blue');
// set selected one to yellow
d3.select(this)
.style('fill', 'yellow');
}
Upvotes: 1