Skip to content

Instantly share code, notes, and snippets.

@brennanpincardiff
Last active August 29, 2015 14:05
Show Gist options
  • Save brennanpincardiff/8e56ef6f51564955aeea to your computer and use it in GitHub Desktop.
Save brennanpincardiff/8e56ef6f51564955aeea to your computer and use it in GitHub Desktop.
More efficient code to create a radio selector
<!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" checked> 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);
// Create a rectangle.
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", "blue");
// Waiting for input
d3.selectAll("input").on("change", change);
var timeout = setTimeout(function() {
d3.select("input[value=\"color\"]")
.property("checked", true)
.each(change);
}, 2000);
// What to do when input is received - run the right function
function change() {
clearTimeout(timeout);
if (this.value === "red") transition("red");
if (this.value === "blue") transition("blue");
if (this.value === "yellow") transition("yellow");
}
// function for drawing a rectange
function transition(color) {
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", color);
}
</script>
</body>
</html>
@brennanpincardiff
Copy link
Author

It occurred to me that I could improve my code by having only one function and passing the color into the function rather than having three functions as detailed in
http://bl.ocks.org/brennanpincardiff/6dc3a53908c2e8611498

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment