Skip to content

Instantly share code, notes, and snippets.

@nkabrown
Last active June 7, 2016 18:03
Show Gist options
  • Save nkabrown/7a596595776462f7a54e9a665ad1f434 to your computer and use it in GitHub Desktop.
Save nkabrown/7a596595776462f7a54e9a665ad1f434 to your computer and use it in GitHub Desktop.
selection ui
<!DOCTYPE html>
<meta charset="utf-8">
<title>D3 Selection UI</title>
<style>
html,
body {
margin: 0;
padding: 0;
}
.container {
width: 90%;
margin: 0 auto;
}
.selection-ui-container {
display: flex;
justify-content: space-around;
flex-wrap: wrap;
width: 60%;
height: 200px;
margin: 0 auto;
margin-top: 15%;
}
.swatch {
display: flex;
justify-content: center;
align-items: center;
border-radius: 50%;
width: 105px;
height: 105px;
margin: 5px 0;
}
.order-marker {
font-family: "Avenir", sans-serif;
font-size: 2.5em;
color: #fff;
}
</style>
<div class="container">
<div class="selection-ui-container"></div>
</div>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
const colors = ['yellow green', 'green', 'blue green', 'blue', 'blue purple', 'purple', 'red purple', 'red', 'orange red', 'orange', 'yellow orange', 'yellow'];
const colorMap = d3.scale.ordinal()
.domain(['yellow green', 'green', 'blue green', 'blue', 'blue purple', 'purple', 'red purple', 'red', 'orange red', 'orange', 'yellow orange', 'yellow'])
.range(['rgb(180,255,27)', 'rgb(34,255,3)', 'rgb(47,104,180)', 'rgb(0,0,255)', 'rgb(125,34,249)', 'rgb(142,0,239)', 'rgb(226,41,103)', 'rgb(251,0,5)', 'rgb(253,127,39)', 'rgb(253,149,10)', 'rgb(254,232,30)', 'rgb(255,255,11)']);
d3.select('.selection-ui-container').selectAll('.swatch')
.data(colors)
.enter().append('div')
.attr('class', 'swatch')
.style('background-color', d => colorMap(d))
.append('p')
.attr('class', 'order-marker')
.text((d, i) => i);
const swatches = d3.selectAll('.swatch');
swatches.on('click', function(d) {
const selectedItem = d;
const selectedElement = d3.select(this);
if (selectedElement.classed('selected')) {
swatches.style('opacity', 1);
selectedElement.classed('selected', false);
} else {
swatches.classed('selected', false);
selectedElement.classed('selected', true);
swatches.filter(s => s !== selectedItem).style('opacity', 0.3);
swatches.filter(s => s === selectedItem).style('opacity', 1);
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment