Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 javascript alternate colors on click

I'm just starting playing around with d3, and was wondering how you could alternate the colors of a element upon clicking it.

This fiddle changes the color of the circle clicking it, but then I'd like to get the color back to being white after clicking again.

Current Code:

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(){d3.select(this).style("fill", "magenta");});
like image 209
reptilicus Avatar asked Jun 07 '12 20:06

reptilicus


1 Answers

Make yourself a toggle function and pass it into the click: http://jsfiddle.net/maniator/Bvmgm/6/

var toggleColor = (function(){
   var currentColor = "white";

    return function(){
        currentColor = currentColor == "white" ? "magenta" : "white";
        d3.select(this).style("fill", currentColor);
    }
})();
like image 75
Naftali Avatar answered Oct 12 '22 00:10

Naftali