Skip to content

Instantly share code, notes, and snippets.

@marcdhansen
Last active August 29, 2015 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcdhansen/c50e688e2b3a36c50d52 to your computer and use it in GitHub Desktop.
Save marcdhansen/c50e688e2b3a36c50d52 to your computer and use it in GitHub Desktop.
Yet another example of append/update/exit (this one with animated transition)

Click to add elements.

Hit any key to remove an element.

Appended elements appear in red.

Note: We begin with two <p> tags and this data array: [0, 1, 2]. So the first time through, the '2' element is not initially bound to a <p> tag. The first click will add a '3' element and append <p>'s for all the unbound elements. In this case, two new <p> tags will be added (for the '2' element and the new '3' element).

For a simpler example without animated transitions, see: Yet another example of append/update/exit

<!DOCTYPE html>
<meta charset="utf-8">
<style>/* CSS */</style>
<body>
<p></p>
<p></p>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var data = [0,1,2];
var body = d3.select("body");
// draw existing entries in black
function blackenAndGetPs(){
var allPs = body
.selectAll("p");
allPs
.transition().duration(1000)
.style("color", "black");
return allPs;
}
var ps = blackenAndGetPs();
ps
.data(data)
.text(String);
// click to add an element
document.addEventListener("click", function() {
ps = blackenAndGetPs();
data.push( data.length );
// enter
ps
.data(data)
.enter()
.append("p")// update new entries:
.text(String)
.style("color", "red")
.style("opacity", 0)
.transition().duration(1000)
.style("opacity", 1);
});
// press key to remove element
document.addEventListener("keydown", function() {
ps = blackenAndGetPs();
data.pop();
// exit
ps
.data(data)
.exit()
.transition().duration(1000)
.style("opacity", 0)
.remove();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment