Last active
July 26, 2017 19:04
-
-
Save denisemauldin/2d0885ba731d1ee2c78bf7d4ecff33da to your computer and use it in GitHub Desktop.
Use g containers with elements inside
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<html> | |
<head> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<style> | |
#svg1 { | |
border: thin solid red; | |
} | |
.circles { | |
fill: red; | |
} | |
</style> | |
</head> | |
<body> | |
<svg id="svg1" width="60" height="60"></svg> | |
<button id="update" type="text/button">Update</button> | |
<button id="reset" type="text/button">Reset</button> | |
<script> | |
let inputData = [ | |
{ id: 1, x: 10, y: 10 }, | |
{ id: 2, x: 30, y: 30 }, | |
{ id: 3, x: 50, y: 50 }, | |
]; | |
function join1(data) { | |
// select the container elements | |
let containers = d3.select("#svg1") | |
.selectAll('.container') | |
.data(data); | |
// select entering elements and append a g element | |
let enterSel = containers.enter() | |
.append("g") | |
.attr("class", "container"); | |
// select exiting elements | |
let exitSel = containers.exit(); | |
// select elements that remain | |
let mergeSel = containers.merge(enterSel); | |
// add a text label to each container | |
enterSel.append("text").attr("text", "label"); | |
// add a circle to each container | |
let circlesEnter = enterSel.append("circle"); | |
// add styles and data to new and remaining elements | |
let circlesMerge = mergeSel | |
.select("circle") | |
.attr("class", "circles") | |
.attr("r", d => 10) | |
.attr("cx", d => d.x) | |
.attr("cy", d => d.y); | |
// remove exiting elements | |
exitSel.remove(); | |
} | |
join1(inputData); | |
d3.select("#reset").on("click", function() { | |
d3.select("#svg1").selectAll("g").remove(); | |
inputData = [ | |
{ id: 1, x: 10, y: 10 }, | |
{ id: 2, x: 30, y: 30 }, | |
{ id: 3, x: 50, y: 50 }, | |
]; | |
join1(inputData); | |
}); | |
d3.select("#update").on("click", function() { | |
inputData = [ | |
{ id: 1, x: 10, y: 10 }, | |
{ id: 2, x: 40, y: 40 }, | |
{ id: 3, x: 10, y: 50 }, | |
{ id: 4, x: 50, y: 10 }, | |
]; | |
join1(inputData); | |
}); | |
</script> | |
</body> | |
</html> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment