javascript – D3.Js Clicking function with a text box or alert box-ThrowExceptions

Exception or error:

Hi I am trying to have a clicking feature with my circles that will allow me to have a text box appear when clicked. I have looked up documentation online but I am just missing something kinda dumb I feel like. Any ideas?


<!DOCTYPE html>
<html>
<head>
    <script src="https://d3js.org/d3.v5.js"></script>
</head>
<body>
    <div id="viz"></div>
    <script type="text/javascript">

    var sampleSVG = d3.select("#viz")
        .append("svg")
        .attr("width", 200)
        .attr("height", 200);

    sampleSVG.append("circle")
        .style("stroke", "red")
        .style("fill", "blue")
        .attr("r", 40)
        .attr("cx", 150)
        .attr("cy", 150)

    sampleSVG.append("circle")
        .style("stroke", "red")
        .style("fill", "purple")
        .attr("r", 20)
        .attr("cx", 50)
        .attr("cy", 50)



    </script>
</body>


How to solve:

How about adding an event handler using the on() method?

Check the example below, which activates a simple alert box.

You can checkout the D3 documentation regarding Handling Events.

const sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 200)
.attr("height", 200);

sampleSVG.append("circle")
  .style("stroke", "red")
  .style("fill", "blue")
  .attr("r", 40)
  .attr("cx", 150)
  .attr("cy", 150)
  .on("click", function(){ alert(); }); // On "click" execute function

sampleSVG.append("circle")
  .style("stroke", "red")
  .style("fill", "purple")
  .attr("r", 20)
  .attr("cx", 50)
  .attr("cy", 50)
  .on("click", function(){ alert(); }); // On "click" execute function

Leave a Reply

Your email address will not be published. Required fields are marked *