Reputation: 3791
I am trying to turn several polygons into buttons in d3. I need each polygon to have a different roll over/roll out/click actions. I draw polygons like this:
poly = [coordinates];
poly2 = [coordinates];
//drawing polygons
chart.selectAll("polygon")
.data([poly, poly2])
.enter().append("polygon")
.attr(... //attributes go here
//I add functionality below
.on("mouseover", function (d) {
chart.selectAll("polygon")
.attr("fill","orange");
})
.on("mouseout" , function (d) {
chart.selectAll("polygon")
.attr("fill","steelblue");
});
This applies all "on mouse..." effects to all polygons. What is the best way to assign different "on mouse..." actions to each polygon? For example, I want poly
to switch color to orange
on mouseover, but poly2
to turn red
on mouseover.
Here is my fiddle with the polygon "buttons", but I was only able to assign the same action to both polygons there.
Upvotes: 1
Views: 160
Reputation: 32327
My approach would be to set the hover color inside the data:
Something like this:
poly2 = {
color: "green",//mouse hover color
points: [{
"x": 71,
"y": 1.5
}, {
"x": 75,
"y": 0
}, {
"x": 79,
"y": 1.5
}, {
"x": 75.5,
"y": 1.1
}, {
"x": 75.5,
"y": 1.7
}, {
"x": 74.5,
"y": 1.7
}, {
"x": 74.5,
"y": 1.1
}]
};
Next on mouse hover instead of selecting all polygons like this:
chart.selectAll("polygon")
.attr("fill","orange");
Select the one which triggered it and set the fill color from the data (check above hover color is passed in the data):
d3.select(this)
.attr("fill", d.color);//fill color from the data defining the polygon.
Working code here
Upvotes: 2
Reputation: 36
One way you could do something like this would be to assign classes to each polygon based on its index:
.attr("class", function(d, i) {return i})
The d is the data and the i is the index, so we are returning the index of each polygon as the class. This allows us to do things like this:
.attr("fill", function(d, i) { return (i === 0) ? "steelblue" : "red";})
So something like this in what you had: https://jsfiddle.net/szjn7u1v/3/.
Upvotes: 1