JSFiddle - React, Tailwind, and code Playground
HTML
<h3>Selecting multiple shapes in a group with shared attributes</h3>
CSS
body {
font-family: sans-serif;
}
circle {
fill: red;
}
ellipse {
fill: blue;
}
rect {
fill: yellow;
}
JavaScript
var dataset = ["A", "B", "C"];
// Create SVG object
var svg = d3.select("body")
.append("svg")
.attr({width: 600, height: 400});
var shapes = svg.append("g");
// Circles
var circles = shapes.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("id",function(d, i) {return i;})
.attr("cx",125)
.attr("cy",function(d, i) {return (i+1)*100-25;})
.attr("r",25)
.on("mouseover", over)
.on("mouseout", out)
.append("title").text(function(d, i) {return d + " " + i;});
// Ellipses
var ellipses = shapes.selectAll("ellipse")
.data(dataset)
.enter()
.append("ellipse")
.attr("cx", 350)
.attr("cy",function(d, i) {return (i+1)*100-25;})
.attr("rx",50)
.attr("ry",25)
.on("mouseover", over)
.on("mouseout", out)
.append("title").text(function(d, i) {return d + " " + i;});
// Squares
var squares = shapes.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", 200)
.attr("y",function(d, i) {return (i+1)*100-50;})
.attr("height",50)
.attr("width",50)
.on("mouseover", over)
.on("mouseout", out)
.append("title").text(function(d, i) {return d + " " + i;});
// Over function to be called on mouseover
function over(d, i) {
shapes.selectAll("circle").filter(function(e, j) {return j == i;})
.style("fill", "green");
shapes.selectAll("rect").filter(function(e, j) {return j == i;})
.style("fill", "green");
shapes.selectAll("ellipse").filter(function(e, j) {return j == i;})
.style("fill", "green");
}
// Out function to be called on mouseout
function out(d, i) {
shapes.selectAll("rect").filter(function(e, j) {return j == i;})
.style("fill", null);
shapes.selectAll("circle").filter(function(e, j) {return j == i;})
.style("fill", null);
shapes.selectAll("ellipse").filter(function(e, j) {return j == i;})
.style("fill", null);
}