By default, the D3 hierarchy will collapse to the first level

I've been working on code to create an indented tree structure. My goal is to initially collapse the tree and show only the first level children or the root node. I tried a few different approaches, but none were successful. The current portion I have below was my latest attempt:

function toggleAll(d) {
    if (d.children) {
        d.children.forEach(toggleAll);
        toggle(d);
    }
}

root.children.forEach(toggleAll);
toggle(root);
});

Below is the HTML along with the corresponding flare.json file:

<meta charset="utf-8">
<style>

.node rect {
  cursor: pointer;
  fill: #fff;
  fill-opacity: 0.8;
  stroke: #3182bd;
  stroke-width: 1.5px;
}

.node text {
  font: 10px sans-serif;
  pointer-events: none;
}

.link {
  fill: none;
  stroke: #9ecae1;
  stroke-width: 1.5px;
}

</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>

// JavaScript code for creating the tree structure

</script>

The content of flare.json:

"name": "flare",
"children": [
 {
  "name": "vis",
  "children": [
   {
    "name": "events",
    "children": [
     {"name": "DataEvent", "size": 2200},
     {"name": "SelectionEvent", "size": 1400},
     {"name": "TooltipEvent", "size": 1200},
     {"name": "VisualizationEvent", "size": 825}
    ]
   }
  ]
 }
]
}

Answer №1

Improving your code by incorporating the toggle(Click) function once the data is loaded. Check out the demo below to see if this aligns with your requirements or if you are looking for something different:

var margin = {
        top: 30,
        right: 20,
        bottom: 30,
        left: 20
    },
    width = 960,
    barHeight = 20,
    barWidth = (width - margin.left - margin.right) * 0.8;

var i = 0,
    duration = 400,
    root;

var diagonal = d3.linkHorizontal()
    .x(function(d) {
        return d.y;
    })
    .y(function(d) {
        return d.x;
    });

var svg = d3.select("body").append("svg")
    .attr("width", width) // + margin.left + margin.right)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var flare = getFlare();
//d3.json("flare.json", function(error, flare) {
//    if (error) throw error;
    root = d3.hierarchy(flare);
    root.x0 = 0;
    root.y0 = 0;
    update(root);

    function toggleAll(d) {
        if (d.children) {
            d.children.forEach(toggleAll);
            //toggle(d);
            click(d)
        }
    }

    root.children.forEach(toggleAll);
    //toggle(root);
//});

Please note that the rest of the code has been omitted for brevity.

Answer №2

I am here to offer assistance.

Observing closely:

function toggleAll(d) {
                   if (d.children) {
                   d.children.forEach(toggleAll);
                  toggle(d);
                   }
               }

                 root.children.forEach(toggleAll);
                  toggle(root);
                  });

In my opinion,

                  });

does not belong there.

Impressive recursive function!
Simply reformatting it:

function toggleAll(d) {
  if (d.children) {
    d.children.forEach(toggleAll);
    toggle(d);
  }
}

A slight adjustment for calling it:

toggleAll(root);

This will toggle everything off. Please note: if something is already toggled off (via click), it will be toggled on,
and then

toggle(root);

This will only toggle the root back on.

I hope this explanation clarifies things!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery not refreshing properly

I'm currently in the process of creating a script to switch the language on a website using PHP and Ajax/jQuery. I would like the page content to refresh without having to reload the entire page. So far, this is what I have come up with: $( "a[data-r ...

The functionality of scrolling ceases to work once the bootstrap modal is closed

I am utilizing Bootstrap v3.1.1 to showcase a modal popup on one of my web pages. The following code shows how I have implemented it. <!--Start show add student popup here --> <div class="modal fade" id="add-student" tabindex="-1" role="dialog" a ...

Consistently encountering incorrect values during onClick events

I am using a Table to display certain values const [selected, setSelected] = React.useState<readonly number[]>([]); const isSelected = (id: number) => selected.indexOf(id) !== -1; return ( <TableContainer> <Table sx={{ width ...

A guide on converting a Javascript datetime to a C# DateTime parameter

In a previous question that I asked on StackOverflow, I mentioned that I was able to retrieve my values successfully as the object was no longer null. The object contains a DateTime property named CreatedOn, which I am sending from JavaScript using new Dat ...

Leveraging the power of JavaScript Math methods to dictate the Co-ordinates of HTML Canvas .fillRect

Greetings to everyone! I have dedicated my entire evening to understanding how to implement the (Math.floor(Math.random()) function as the coordinates for the .fillRect method on an HTML canvas element. Despite searching through this website and various ...

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Iterating through an array with a .forEach loop and referencing the variable name

Currently, I am working on a project using JS/React and dealing with nested arrays in an array. The structure of my data looks like this: const ezra = ["Patriots", "Bears", "Vikings", "Titans", "Jets", "Bengals"] const adam = ["Chiefs", "Cowboys", "Packer ...

The Arrow notations don't seem to be functioning properly in Internet Explorer

Check out my code snippet in this JSFiddle link. It's working smoothly on Chrome and Mozilla, but encountering issues on IE due to arrow notations. The problem lies within the arrow notations that are not supported on IE platform. Here is the specifi ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

When previewing a card on Twitter's validator tool, the image displays properly. However, when attempting to share the image on

Below is the code that I have written on my HTML page: <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:site" content="@name" /> <meta name="twitter:title" content="Twitter - image share" /> <meta name="twi ...

Stylish hover effects displayed on disabled button using Styled Components

I am currently working on a button using Styled Components. However, even when the button is in a disabled state (:disabled), it still exhibits hover behavior that should not be present. I am wondering if there is a proper way to prevent hover effects when ...

Can the mui dialog actions button be activated using CTRL + S?

Is it feasible to enable my users to save content in a MuI dialog by pressing CTRL + S? ...

Breaking down objects or arrays to extract specific values in React components

Some articles recommend using ES6 destructuring for React props & state as a best practice. For example: const { showModal, hideModal } = this.props; While I understand the benefits of cleaner code, I recently discussed with another developer who suggest ...

Converting a date from PHP to JavaScript

My PHP code generates the following date: <?php date_default_timezone_set('Europe/London'); echo date('D M d Y H:i:s O'); ?> Additionally, I have a JavaScript/jQuery script that displays this date on the website: setInterval( ...

How can I use XPATH to target a div after choosing a nested element?

I had the task of creating a universal identifier to locate a dropdown menu following a label. There are 10 different forms, each with a unique structure but consistent format, which means I cannot rely on specific IDs or names. Instead, my approach was to ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Vue-quill-editor causes lists to incorrectly display <br> tags when using Quill, resulting in unwanted formatting additions

My application relies on vue-quill-editor for users to create notes. Initially, when a user creates a list, it is saved correctly. For instance, the saved HTML may appear as follows: <div> Test: </div> <ol> <li> One </l ...

Excessive CPU/GPU usage caused by CSS transition animations

I am currently working on a small element on my website that involves a random size change in one of the DOM elements. const theDiv = document.getElementById("the-div"); function animate(){ const value = Math.floor(Math.random() * 200); theDiv.sty ...

Does Vuex dispatch from within a component include a particular type of behavior known as a "promise"?

Currently, I am diving into vuex and facing an issue. During the created() lifecycle hook, my goal is to fetch data from an API. Once this action is complete, I need to call a getter from the component and assign the retrieved cards to the component's ...