2
votes

I'm trying to get d3 to change the color of plot points upon clicking them, but can't seem to get this working at the moment. The commented line below does change the color from white to magenta, but the toggleColor function does not seem to do anything. Actually, the alert only happens when first run, and not when a point is clicked. What am I doing wrong here?

var circle = graph.selectAll("circle.value")
    .data(data)
    .enter().append("circle")
    .attr("class", "value")
    .attr("cx", function(d) { return x(d.hour); })
    .attr("cy", function(d) { return y(d.value); })
    .attr("r", 5)
    //.on("click", function(){d3.select(this).attr("class", "flagged");});
    .on("click", toggleColor);


var toggleColor = (function(){
    // throw in an alert for good measure. . .
    alert("Clicked?")
    var currentColor = "white";
    return function(){

        currentColor = currentColor == "white" ? "magenta" : "white";
        d3.select(this).atrr("class", "flagged");
    }
   })();

1

1 Answers

4
votes

To begin with, var toggleColor is still undefined at the point where you're wiring up the click event (because it's defined further down the page). So you need to move it up.

Then, the reason the alert appears only once, at runtime, is because that's when that code is run. If you notice, the outer function is executed right after it's declared, as evident by the () at the very last line of the code. That's when alert() gets called. You'll want to move it into the body of the inner function -- the one that's returned -- because that inner function is the code that will actually run on click.