Skip to content

Instantly share code, notes, and snippets.

@brennanpincardiff
Last active August 29, 2015 14:05
Show Gist options
  • Save brennanpincardiff/d07d52f10900c14844b5 to your computer and use it in GitHub Desktop.
Save brennanpincardiff/d07d52f10900c14844b5 to your computer and use it in GitHub Desktop.
Even more simple code to change color with a dialog box

This code is more efficient yet. The box is drawn black first and then the color is changed by selecting the relevant button. I didn't need the timeout function. I can do all the drawing in one function. No need for if statements. Simplied version of http://bl.ocks.org/brennanpincardiff/8e56ef6f51564955aeea

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
<title> Using Radio Box to change color of a square </title>
<script src=http://d3js.org/d3.v3.min.js></script>
</head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: auto;
position: relative;
width: 960px;
}
form {
position: absolute;
left: 0px;
top: 0px;
}
</style>
<body>
<form>
<label><input type="radio" name="mode" value="red"> Red</label>
<label><input type="radio" name="mode" value="blue" > Blue</label>
<label><input type="radio" name="mode" value="yellow"> Yellow</label>
</form>
<script>
// Generate an svg container
var svgContainer = d3.select("body")
.append("svg")
.attr("width", 400)
.attr("height", 400);
// Draw a black rectangle first.
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", "black");
// Wait for input
d3.selectAll("input").on("change", transition);
// now depending selection, draw a colored rectangle.
function transition() {
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", this.value); // this.value is picked up from the input
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment