Skip to content

Instantly share code, notes, and snippets.

@jfreels
Last active December 24, 2015 16:39
Show Gist options
  • Save jfreels/6829400 to your computer and use it in GitHub Desktop.
Save jfreels/6829400 to your computer and use it in GitHub Desktop.
d3js: Update multiple SVG circles with Select input.

d3js: Update multiple SVG circles with Select input.

<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
var data = { "red" : [ { "cx" : 50, "cy" : 50, "r" : 20, "fill" : "red" } ],
"blue" : [ { "cx" : 100, "cy" : 100, "r" : 30, "fill" : "blue" },
{ "cx" : 200, "cy" : 200, "r" : 15, "fill" : "blue" } ],
"green" : [ { "cx" : 150, "cy" : 150, "r" : 40, "fill" : "green" },
{ "cx" : 50, "cy" : 50, "r" : 20, "fill" : "green" },
{ "cx" : 200, "cy" : 200, "r" : 30, "fill" : "green"} ]
}
var w = 500
var h = 500
var body = d3.select('body')
body.append('select')
.on('change',updateCircles)
.selectAll('option')
.data(d3.keys(data))
.enter()
.append('option')
.attr('value',function (d) { return d })
.text(function (d) { return d })
body.append('br')
var svg = body.append('svg')
.attr('width',w)
.attr('height',h)
svg.selectAll('circle')
.data(data.red)
.enter()
.append('circle')
.attr('r',0)
.attr('fill', function (d) { return d.fill })
.on('click', function () {
d3.select(this)
.transition().duration(1000)
.attr('r',0)
.remove()
})
.transition().duration(1000)
.attr('cx', function (d) { return d.cx })
.attr('cy', function (d) { return d.cy })
.attr('r', function (d) { return d.r })
.attr('fill', function (d) { return d.fill })
function updateCircles() {
var selectValue = d3.select('select').property('value')
var data2 = data[selectValue]
var circles = svg.selectAll('circle')
.data(data2)
circles.transition().duration(1000)
.attr('cx', function (d) { return d.cx })
.attr('cy', function (d) { return d.cy })
.attr('r', function (d) { return d.r })
.attr('fill', function (d) { return d.fill })
circles.enter()
.append('circle')
.attr('r', 0)
.attr('fill', function (d) { return d.fill })
.on('click', function () {
d3.select(this)
.transition().duration(1000)
.attr('r',0)
.remove()
})
.transition().duration(1000)
.attr('cx', function (d) { return d.cx })
.attr('cy', function (d) { return d.cy })
.attr('r', function (d) { return d.r })
circles.exit()
.transition().duration(1000)
.attr('r',0)
.remove()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment