3yakuya 3yakuya -4 years ago 106
Javascript Question

D3 - show/hide text of only clicked node

I am trying to show/hide text of a node in D3 on click. I tried using the following code:

var node = svg.selectAll(".node")
.data(json.nodes)
(...)

node.on("click", function() {
if (textShowing) {
node.select("text").style("visibility", "hidden");
} else {
node.select("text").style("visibility", "visible");
}
textShowing = !textShowing;
});


The code results in text property of all nodes showing/disappearing on click of any of those.

How can I affect the text property of only the clicked node?

Answer Source

node is a selection containing all your groups (I suppose they are groups, since you didn't copy/paste the entire selection).

If you want to do anything only in the clicked group, you have to select it using d3.select(this), which selects the current (in your case, the clicked) DOM element.

Thus, instead of:

node.select("text")

It should be:

d3.select(this).select("text")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download