Skip to content

Instantly share code, notes, and snippets.

@rarpal
Last active October 29, 2015 13:20
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 rarpal/8c1c427d78d95f8efa0b to your computer and use it in GitHub Desktop.
Save rarpal/8c1c427d78d95f8efa0b to your computer and use it in GitHub Desktop.
D3js Enter, Update and Exit demo
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
</head>
<body>
<script language="javascript">
var scale = d3.scale.linear()
.domain([1, 5]) // Data space
.range([0, 200]); // Pixel space
var svg = d3.select("body").append("svg")
.attr("width", 250)
.attr("height", 250);
function render(data, color) {
var rects = svg.selectAll("rect").data(data);
// Enter
rects.enter().append("rect")
.attr("y", 50)
.attr("width", 20)
.attr("height", 20);
// Update
rects
.attr("x", scale)
.attr("fill", color);
// Exit
rects.exit().remove();
}
setTimeout(function () { render([1, 2, 2.5], "red"); }, 1000);
setTimeout(function () { render([1, 2, 3, 4, 5], "blue"); }, 2000);
setTimeout(function () { render([1, 2], "green"); }, 3000);
setTimeout(function () { render([3, 4, 5], "cyan"); }, 4000);
setTimeout(function () { render([4, 5], "magenta"); }, 5000);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment