Reputation: 37
I am new to D3 and i'm stuck on a case. I have a button that adds circles to my svg.
d3.select("button#add").on("click", function()
{
svg.append('circle')
.attr('class', 'little')
.attr("cx", Math.random()*280+10)
.attr("cy",Math.random()*280+10)
.attr("r", 12);
});
Afterwards I would like to change the color when you click on a circle. For some reason the code doesn't even start the event.
d3.selectAll(".little").on('click', function()
{
d3.select(this).style("fill", "red");
});
Upvotes: 1
Views: 4088
Reputation: 464
The issue lies in the fact that this:
d3.selectAll(".little").on('click', function() {
d3.select(this).style("fill", "red");
});
only runs once. But when the button click creates a new circle, it creates it without adding the onclick property, and since the above code isn't run again, the new circle has no event listeners for click.
To fix it, just add the .on part while creating the circle, or make sure that the above code is run every time a new circle is made (I don't really recommend doing it this way unless your callback function is being changed every time).
Upvotes: 0
Reputation: 5015
Here is a FIDDLE to help you out.
...
function paintCircle(d) {
d3.select(this)
.style("fill", "red");
};
Upvotes: 1