Skip to content

Instantly share code, notes, and snippets.

@pbogden
Last active August 29, 2015 14:27
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 pbogden/13f1a9643749ba368fd7 to your computer and use it in GitHub Desktop.
Save pbogden/13f1a9643749ba368fd7 to your computer and use it in GitHub Desktop.
readd

add/remove/readd DOM elements

<!DOCTYPE html>
<meta charset="utf-8">
<title>readd</title>
<style>
form {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 30px;
color: lightgray;
position: absolute;
left: 100px;
top: 60px;
}
rect {
stroke: gray;
stroke-width: 5px;
fill: crimson;
}
.removed {
color: crimson;
}
</style>
<body>
<form>
<input type="radio" name="choice" value="add" checked> Add<br>
<input type="radio" name="choice" value="remove"> Remove
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js"></script>
<script>
var margin = {top: 20, right: 120, bottom: 20, left: 20},
width = 600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var rect = svg.append("rect")
.attr("width", width)
.attr("height", height);
// Use form buttons to toggle the rect element
d3.selectAll("input").on("change", changed);
function changed() {
if (this.value == "add") {
svg.append(function() { return rect[0][0]; });
rect = null;
d3.select("form").classed("removed", false);
} else {
rect = d3.select("rect").remove();
d3.select("form").classed("removed", true);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment