|
<!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> |
Learning how to generate interactive events in d3.
Inspired by http://bl.ocks.org/mbostock/3943967