Last active
April 5, 2016 09:14
-
-
Save clemsos/ff551e9c8ffb8224dfd3719672e1e79a to your computer and use it in GitHub Desktop.
D3 simple color selector
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//data (pass your color | |
var c20 = d3.scale.category20c(); | |
var colors = d3.range(20).map(function(i){ return c20(i) }); | |
var selectedColor = "black"; | |
var h = 100, | |
w = 400, | |
colorOpened = false, | |
paddingX = 10 | |
radius = 10; | |
var svg = d3.select("svg") | |
.attr({ | |
width: w, | |
height: y | |
}); | |
var y = h/2; | |
var x = d3.scale.linear().domain([-1, colors.length]).range([0, w]); | |
svg.append("g") | |
.attr("class","selector") | |
.selectAll("circle") | |
.data(colors) | |
.enter() | |
.append("circle") | |
.attr("class", "color-selector-item") | |
.attr("r", radius ) | |
.attr("cx", paddingX) | |
.attr("cy", y) | |
.attr("fill", function(d){return d } ) | |
.on("click",function(d,i) { | |
d3.select(".trigger").attr("fill",d); | |
closeColors(); | |
callback(d); | |
}) | |
// trigger | |
svg.append("circle") | |
.attr("class","trigger") | |
.attr("r", radius ) | |
.attr("cy", y) | |
.attr("cx", paddingX) | |
.attr("fill", selectedColor) | |
.on("click", function(d){ | |
console.log("action ! ") | |
colorOpened = !colorOpened; | |
if(colorOpened) openColors(); | |
else closeColors(); | |
}) | |
var openColors = function () { | |
d3.selectAll(".color-selector-item") | |
.transition() | |
.duration(1000) | |
.attr("cx", function(d,i){ | |
return radius + x(i); | |
}); | |
colorOpened = true; | |
} | |
var closeColors = function () { | |
d3.selectAll(".color-selector-item") | |
.transition() | |
.duration(1000) | |
.attr("cx", function(d,i){ | |
return paddingX | |
}); | |
colorOpened = false; | |
} | |
var callback = function(color) { | |
console.log("do whatever you want with ", color); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment