1

I'm new to javascript. I'm using D3 to build some charts. I'm wanting to display the number of mouse clicks over an SVG element.

Currently I can display the ellipse and can track the number of clicks on the ellipse. I'm wanting to overlay the changing number of mouse clicks on the ellipse.

I have it working so that the initial variable is displayed, but haven't been able to solve how to display the variable changes (ie additional mouse clicks). I want it so that as soon as the ellipse is clicked on, the text is updated.

My code is below.

<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
    <div id="viz"></div>
    <script type="text/javascript">
    var clicks = 0;
    var sampleSVG = d3.select("#viz")
        .append("svg:svg")
        .attr("width", 400)
        .attr("height", 800);    
    sampleSVG.append("svg:ellipse")
        .style("stroke", "gray")
        .style("fill", "white")
        .attr("rx", 20)
        .attr("ry", 25)
        .attr("cx", 50)
        .attr("cy", 50)
        .on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
        .on("mouseout", function(){d3.select(this).style("fill", "white");})
        .on("click", function(){clicks = clicks+1
                    })
    sampleSVG.append("svg:text")
        .text(clicks)
        .attr("x", 50)
        .attr("y", 50)
        .attr("fill", "black"); 
    </script>
</body>
</html>

I tried adding to sampleSVG.text(clicks) to my onclick function, but it didn't work.

Also as a more general question, should my text (var clicks) be appended to sampleSVG or should I create a new variable sampleText and overlay it over sampleSVG?

THanks for the help

R

1 Answer 1

2

Saying sampleSVG.text(clicks) sets the text content of the outer svg:svg element, deleting all the contained elements; you want to set the text content of just the svg:text element. You could select the text element on click:

.on("click", function() {
  clicks = clicks + 1;
  sampleSVG.select("text").text(clicks);
})

Alternatively, when you create the text element, you could save a reference to it:

var sampleText = sampleSVG.append("text")
    .text(clicks)
    .attr("x", 50)

Then you can access this element on click:

.on("click", function() {
  clicks = clicks + 1;
  sampleText.text(clicks);
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.