Skip to content

Instantly share code, notes, and snippets.

@maelp
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maelp/11522092 to your computer and use it in GitHub Desktop.
Save maelp/11522092 to your computer and use it in GitHub Desktop.
Fast prototyping tricks - Sorting elements
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
width: 960px;
padding-top: 40px;
margin: auto;
position: relative;
}
svg {
width: 100%;
max-height: 400px;
font-family: sans-serif;
}
</style>
<svg width='400px' height='100px' viewBox='0 0 500 100' style='fill:#f48'>
<g id='group-unsorted' transform='translate(25, 50)'>
<circle cx='0' cy='0' r='10'></circle>
<circle cx='100' cy='0' r='10'></circle>
<circle cx='50' cy='0' r='10'></circle>
<circle cx='150' cy='0' r='10'></circle>
<text x='75' y='50' style='fill:#444;text-anchor:middle'>Without sort</text>
</g>
<g id='group-sorted' transform='translate(275, 50)'>
<circle cx='0' cy='0' r='10'></circle>
<circle cx='100' cy='0' r='10'></circle>
<circle cx='50' cy='0' r='10'></circle>
<circle cx='150' cy='0' r='10'></circle>
<text x='75' y='50' style='fill:#444;text-anchor:middle'>With sort</text>
</g>
</svg>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script type='text/javascript'>
function animateGrowingCircle(maxRadius, minRadius) {
var animateFunction = function () {
d3.select(this)
.attr('r', minRadius)
.transition()
.duration(1000)
.attr('r', maxRadius)
.transition()
.duration(1000)
.attr('r', minRadius)
.each('end', function () {
d3.select(this).each(animateFunction);
});
};
return animateFunction;
}
window.addEventListener('load', function () {
svg = d3.select('svg');
svg.select('#group-unsorted').selectAll('circle')
.each(function (d, i) {
d3.select(this)
.transition()
.delay(i*250)
.each(animateGrowingCircle(10, 20));
});
svg.select('#group-sorted').selectAll('circle')
.datum(function () {
return {'x': +d3.select(this).attr('cx')};
})
.sort(function (a, b) { return a.x - b.x; })
.each(function (d, i) {
d3.select(this)
.transition()
.delay(i*250)
.each(animateGrowingCircle(10, 20));
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment