I have a button which draws a line and some dots on that line on a graph. I have a second button which removes the line and the dots. I’m trying to use the same button for both functions.
Im having some difficulty with it. Has anyone seen anything like this before?
Here are my two functions. Thanks in advance!
//Draws line and dots
d3.select(".button1").on("click", function(){
var path = svg.append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline(data))
.attr("stroke", "steelblue")
.attr("stroke-width", "5")
.attr("fill", "black");
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("class", "firstDots")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.close); })
var totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + "30" * 30)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(2000)
.ease("linear")
.attr("stroke-dashoffset", 0);
//Removes line and dots
d3.select(".button2").on("click", function(){
path.remove();
var removeDot = svg.selectAll(".firstDots")
.remove();
});
});
At first I tried passing the class of the buttons back and forth on each click event, it works for drawing and removing. But only once, so I am not able to draw the line and second time.
You could move the
pathvariable outside the event-handler: