Click event for d3.js circle pack

dip picture dip · Jan 27, 2014 · Viewed 7.9k times · Source

I am able to draw bubble chart in d3.js. Also when I clicked to any circle, I am getting alert messages. But when I clicked outside circle area,I am still getting alert messages. I do not want any clickable area outside my circle pack. Please help. See my example here.

Data.json

{
"chartData": [
    {
        "name": "Type1",
        "size": 12,
        "color": "red"
    },
    {
        "name": "Type2",
        "size": 28,
        "color": "yellow"
    },
    {
        "name": "Type3",
        "size": 36,
        "color": "blue"
    },
    {
        "name": "Type4",
        "size": 24,
        "color": "green"
    }
]

}

var diameter = 450,
    format = d3.format(",d"), 
    color = d3.scale.category20c();

var bubble = d3.layout.pack()
    .sort(null)
    .size([diameter, diameter]);

var svg = d3.select('#bubbleId').append("svg")
    .attr("width", diameter)
    .attr("height", diameter)
    .attr("class", "bubble");

d3.json("data.json", function(error, root) {

    var node = svg.selectAll(".node")
        .data(bubble.nodes(classes(root))
        .filter(function(d) { return !d.children; }))
       .enter()
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        }
);


node.append("circle")
   .attr("r", function(d) { return d.value; })
   .style("fill", function(d) { return d.color;});

node.on("click", function(d) {
    alert("on click" + d.className); 
});

function classes(root) {
    var classes = [];
    function recurse(name, node) {
        if (node.chartData) {
            node.chartData.forEach(function(child) {
                recurse(node.name, child);
            }); 
        } 
        else{
            classes.push({ packageName: name,
                           className: node.name,
                           value: node.size,
                           color: node.color,
                           totalCount:node.totalCount});
        } 
    } 
    recurse(null, root); 
    return {children: classes};
  }

Answer

FernOfTheAndes picture FernOfTheAndes · Jan 27, 2014

I tried playing with your data structure, etc. but it was just taking too long to clean everything up. Here is a fiddle I forked and added the onclick event to serve as a model for you. It works as predicted. You can study it and apply it to your data.

Here is the snippet I altered from the original fork:

node.append("circle")
    .attr("r", function(d) { return d.r; })
    .style("fill", function(d) { return fill(d.packageName); })
    .on("click", function(d) {
        alert("on click" + d.className);
    });