d3 javascript alternate colors on click
by ninachroscicka
HTML
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script>
</head>
<body>
<div id="viz"></div>
</body>
</html>
JavaScript
function getColor(){
var myArray = ["#007bff","#28a745","#17a2b8","#ffc107","#dc3545"]
return myArray[Math.floor(Math.random() * myArray.length)];
}
z
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);
sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("click", function(){var nextColor = this.style.fill == "white" ? getColor() : "white";
d3.select(this).style("fill", nextColor);});