Skip to content

Instantly share code, notes, and snippets.

@brennanpincardiff
Last active August 29, 2015 14:03
Show Gist options
  • Save brennanpincardiff/6dc3a53908c2e8611498 to your computer and use it in GitHub Desktop.
Save brennanpincardiff/6dc3a53908c2e8611498 to your computer and use it in GitHub Desktop.
Change color with 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") transitionRed();
if (this.value === "blue") transitionBlue();
if (this.value === "yellow") transitionYellow();
}
// function for drawing a red rectange
function transitionRed() {
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", "red");
}
// function for drawing a blue rectange
function transitionBlue() {
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", "blue");
}
// function for drawing a yellow rectange
function transitionYellow() {
var rectangle = svgContainer.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("height", 200)
.attr("width", 200)
.style("fill", "yellow");
}
</script>
</body>
</html>
@brennanpincardiff
Copy link
Author

Learning how to generate interactive events in d3.
Inspired by http://bl.ocks.org/mbostock/3943967

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