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

Dealing with all errors across all pages in Angular using a comprehensive error handling approach

I am currently using AngularJS and attempting to capture all errors across all pages. However, I am encountering an issue where it does not catch errors in some instances. For example, when I trigger a ReferenceError in one of the controllers, it is not be ...

The delete button is designed to remove the record from the database while keeping it visible on the frontend

When the delete button is pressed, it successfully removes the record from the database. However, it does not disappear from the frontend until the page is reloaded or refreshed. This is what I see: @foreach (var item in Model) { <a href="#" ...

Acquiring an icon of a program using its handle

I am looking for a way to extract a program's icon from its handle, which I acquired using User32.dll with EnumWindow/FindWindow. While I am aware of ExtractAssociatedIcon, it seems to work from a file instead of a handle. My question is how can I con ...

Checking for an active listening instance of `http.Server` in a Node application

Having an http server and a piece of code that needs to run only when the server is actively listening, I have bound it to the event "listening" as follows : server.on('listening', doSomething) The issue arises when the server is already listen ...

Steps for connecting an external .otf file in p5.js

I'm struggling to connect a custom font file to my p5.js sketch through a URL in order to upload it on codepen.io. Unfortunately, the font is not available on Google Fonts. I attempted to include the URL in the load font function like this: loadFon ...

What is the most effective method for implementing a debounce effect on a field in React or React Native?

Currently, I am working on implementing a debounce effect in my useEffect. The issue is that the function inside it gets called as soon as there is a change in the input value. useEffect(() => { if (inputValue.length > 0) { fn(); ...

Can we create a process that automatically transforms any integer field into a hashed string?

Is there a non-hacky way to hash all IDs before returning to the user? I have explored the documentation extensively but haven't found a solution that covers all scenarios. I am working with Postgres and Prisma ORM, managing multiple models with rela ...

Is it possible to achieve dynamic updating in Angular without utilizing ng-repeat? (with the use of Firebase)

Is there a way to dynamically update the DOM without utilizing ng-repeat in your template? It appears that when using ng-repeat to load a list of objects, any additions or deletions from the database automatically reflect in the DOM. However, if I simply u ...

Tips for implementing conditional styling (using else if) in a react component

Currently, while iterating through a list of header names, I am attempting to change the CSS style of a react component based on three different conditions. I have managed to make it work for one condition, but I am facing challenges when trying to impleme ...

tips for efficiently using keyboard to navigate through tabs in an unordered list

Utilizing unordered lists in this web application. I am looking to implement tab navigation with keyboard functionality. How can I achieve this? The first tab should contain text boxes, and when the user fills out a text box and presses the tab key, they s ...

Choose to conceal beneath the table within Bootstrap 4

As a budding web developer, I am currently using Bootstrap 4 in my project. If you take a look at my preview by clicking here and then selecting "Liczba sztuk," you'll notice that I am facing an issue. The items within the select dropdown are gettin ...

Modifying canvas border colors using AngularJS

Currently, I am in the process of learning AngularJS and have developed a website that includes a canvas element. My main objective is to change the border color after clicking on a checkbox. Here is the code snippet for canvas.html : <!DOCTYPE html&g ...

positioned absolutely with a margin of 0 auto

Struggling to find a way to center the text in the wrapper? I have a responsive slideshow that requires text to be on top of it and centered. ul.bjqs { position:relative; list-style:none; padding:0; margin:0; z-index: 1; overflow ...

Guidelines for accessing a specific object or index from a dropdown list filled with objects stored in an array

Here is a question for beginners. Please be kind. I have created a select field in an HTML component using Angular, populated from an array of objects. My goal is to retrieve the selection using a method. However, I am facing an issue where I cannot use ...

To complete Mocha tests, ensure to use the done() method. However, keep in mind that the resolution method is too specific. Choose either to specify a callback *or* return a Promise, but not both simultaneously

Encountering a frustrating issue with a mocha test. When I leave it alone, it freezes and displays: Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. If I include `Pro ...

Switching focus between windows while working with React

My current setup involves using React. Every time I run yarn start, I can begin coding and see the changes in my browser. However, there's a recurring issue where my terminal keeps notifying me about errors in my code every 10 seconds or so. This cons ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

Is there a delay in Javascript identifying user existence when retrieving values from ajax?

I'm working on a script that checks if a username already exists before allowing a visitor to proceed. Here's a snippet of the code I'm using: EDIT: I've made some adjustments based on your feedback, but I'm still having trouble g ...

Scroll to make the div slide in from the bottom

I'm trying to achieve a similar effect like the one shown in this website (you need to scroll down a bit to see the divs sliding in). Although I'm not very proficient in JS, I was able to create a code that makes the divs fade in from 0 opacity ...

Simply touch this element on Android to activate

Currently utilizing the following code: <a href="http://www...." onmouseover="this.click()">Link</a> It is evident that this code does not work with the Android Browser. What javascript code will function properly with the Android Browser as ...