Skip to content

Instantly share code, notes, and snippets.

@delgadom

delgadom/index.html

Last active May 21, 2018
Embed
What would you like to do?
Resizable color palette

This creates a dynamic-sized color scheme, linearly interpolated between the two given colors

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<style type="text/css" media="screen">
div.block {
width:60px;
height: 60px;
float: left;
margin: 1px;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.js"></script>
<input type="number" id="numBins" value="12" min="0"> <br/>
<div id='frame'>
<script type="text/javascript">
var frame, blocks, binner, numBins;
frame = d3.select(document.getElementById("frame"));
binner = document.getElementById('numBins');
var update = function() {
numBins = Number(binner.value);
color = d3.scale.linear().domain([1,numBins])
.interpolate(d3.interpolateLab)
.range([d3.rgb("#007AFF"), d3.rgb('#FFF500')]);
blocks = document.getElementsByClassName('block');
if (blocks.length > numBins) {
for (var i = blocks.length; i > numBins; i--) {
blocks[i-1].remove();
}
} else if (blocks.length < numBins) {
for (var i=blocks.length; i < numBins; i++) {
frame.append('div').attr('class', 'block');
}
}
blocks = document.getElementsByClassName('block');
for (var i = Math.max(blocks.length, numBins)-1; i >= 0; i--) {
d3.select(blocks[i]).attr('style', function(d) {
return 'background-color: ' + color(i);
});
}
};
binner.onchange = update;
binner.onclick = update;
update();
</script>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment