Sundararajan
Sundararajan

Reputation: 704

How to add click event on d3.js child of collapsible tree?

I'm using d3.js for collapsible tree structure from here
enter image description here Now my goal is to add a click event on the final child (i.e) Son of A or Daughter of A
For example I need to create an alert box on clicking the childless node.

I tried to add a condition within the click function, but it works only on my second click and I don't get it why the alert box is not getting up on my first click.

Could some one explain me why is it so? and what is the right way to do it?

MY CLICK FUNCTION

function click(d) {
if (d.children) {
    d._children = d.children;
    d.children = null;

  } else {
    d.children = d._children;
    d._children = null;
    if (d.children === null){
        alert(d.id);
    }
  }
update(d);
}

Upvotes: 0

Views: 615

Answers (1)

Gunner
Gunner

Reputation: 746

Instead of using

if (d.children === null){
    alert(d.id);
}

Use

if (!d.children){
    alert(d.id);
}

This is because d.children would be undefined but you were checking for null. Since undefined and null equate to false !d.children check will succeed.

Upvotes: 1

Related Questions