d3: need different behaviour on click depending on node's class attribute
I have a feeling this is a pretty basic misunderstanding on my part.
I'm working from this tree visualisation: http://bl.ocks.org/mbostock/4339083
The original version has the nodes opening and collapsing when the user
clicks on a node that has children. I want to make it so that clicking on
a node that has no children has some other effect (specifically, I want it
to open an image in another window).
So, here's where the on click function is assigned:
var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("class", function(n) {
if (n.children) {
return "inner node"
} else {
return "leaf node"
}
})
.attr("transform", function(d) { return "translate(" + source.y0 + ","
+ source.x0 + ")"; })
.on("click", click);
I have added the second class assignment to differentiate between nodes
with and without children.
This is my modified click function:
function click(d) {
if (d.attr("class") == "inner node") {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
} else if (d.attr("class") == "leaf node") {
// open image
}
update(d);
}
I added the outer if statement to differentiate between the two kinds of
node.
So, currently nothing works when I click. I assume that my
'd.attr("class") == "inner node"' is turning up false, either because the
assignment of that class attribute didn't work, or because what I've
written is gibberish. It doesn't work when I change it to "node" either,
though.
It also occurred to me that the assignment might be scuppered by the fact
that all the nodes start off collapsed - so "n.children" might return
false, even if there are children. Does collapsing the children affect
this?
Any help much appreciated.
------------------------------** EDIT **------------------------------
From playing around a bit, I think I've ascertained that I should have
used "d.class", rather than "d.attr('class')". However, this still doesn't
make it work. I assume that I have misunderstood what d represents here -
is that right?
No comments:
Post a Comment