Question

I am attempting to put 2 d3.js tree diagrams, as seen here http://bl.ocks.org/1249394 on one page. Both trees will be loaded with different data from Javascript objects. The first one will appear in:

<div id="chart"></div>

and the second tree will be loaded in:

<div id="chart2"></div>

Both #chart and #chart2 are on the same page, with the first tree (#chart) appearing at the top of the page, and the 2nd (#chart2) right under it as that is how the chart divs are arranged. To do this I have applied the same code from http://bl.ocks.org/1249394 twice. One for each div with the only difference between the 2 pieces of code being the location of the tree that is tree 1:#chart and tree 2:#chart2.

Tree 1:

var vis = d3.select("#chart").append("svg:svg")

Tree 2:

var vis = d3.select("#chart2").append("svg:svg")

Everything else remains the same including variable and function names. This works great and both diagrams show up as they should, except for the click function (last function in the code: ) Only the second tree is able to collapse and expand on click of tree nodes, the first tree is no longer able to do this, the first is no longer interactive.

How do I fix this?

Was it helpful?

Solution

You are overwriting the vis variable when you draw the second tree which the interaction depends on. If you are going to create multiple charts, you need to create a closure so that each tree is in its own scope. This way they won't interfere with each other.

Mike wrote up a nice post about creating reusable charts at http://bost.ocks.org/mike/chart/. He walks through creating a closure and surfacing properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top