Expand the table in the initial state by using CSS to collapse the tree

I am struggling to collapse the tree view and need assistance. Below is the code snippet I've added. My goal is to have each node in the tree view initially collapsed and then expand a particular node on user interaction.

For example, when I execute this code, it should display item1 and item5. Clicking on item1 should reveal item2 and item4, excluding item3. This illustrates the issue I'm facing.

$(function() {
    $('#mytable').on('click', '.toggle', function () {
        //Gets all <tr>'s  of greater depth
        //below element in the table
        var findChildren = function (tr) {
            var depth = tr.data('depth');
            return tr.nextUntil($('tr').filter(function () {
                return $(this).data('depth') <= depth;
            }));
        };

        var el = $(this);
        var tr = el.closest('tr'); //Get <tr> parent of toggle button
        var children = findChildren(tr);

        //Remove already collapsed nodes from children so that we don't
        //make them visible. 
        //(Confused? Remove this code and close Item 2, close Item 1 
        //then open Item 1 again, then you will understand)
        var subnodes = children.filter('.expand');
        subnodes.each(function () {
            var subnode = $(this);
            var subnodeChildren = findChildren(subnode);
            children = children.not(subnodeChildren);
        });

        //Change icon and hide/show children
        if (tr.hasClass('collapse')) {
            tr.removeClass('collapse').addClass('expand');
            children.hide();
        } else {
            tr.removeClass('expand').addClass('collapse');
            children.show();
        }
        return children;
    });
});
table td {
    border: 1px solid #eee;
}
.level1 td:first-child {
    padding-left: 15px;
}
.level2 td:first-child {
    padding-left: 30px;
}

.collapse .toggle {
    background: url("http://mleibman.github.com/SlickGrid/images/collapse.gif");
}
.expand .toggle {
    background: url("http://mleibman.github.com/SlickGrid/images/expand.gif");
}
.toggle {
    height: 9px;
    width: 9px;
    display: inline-block;   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="mytable">
    <tr data-depth="0" class="collapse level0">
        <td><span class="toggle collapse"></span>Item 1</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse level1">
        <td><span class="toggle"></span>Item 2</td>
        <td>123</td>
    </tr>
    <tr data-depth="2" class="collapse level2">
        <td>Item 3</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse level1">
        <td>Item 4</td>
        <td>123</td>
    </tr>
    <tr data-depth="0" class="collapse collapsable level0">
        <td><span class="toggle collapse"></span>Item 5</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse collapsable level1">
        <td>Item 6</td>
        <td>123</td>
    </tr>
</table>

Answer №1

Update your HTML to set it in the desired default mode. Here is the code snippet:

<table id="mytable">
    <tr data-depth="0" class="expand level0">
        <td><span class="toggle collapse"></span>Item 1</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse level1" style="display: none;">
        <td><span class="toggle"></span>Item 2</td>
        <td>123</td>
    </tr>
    <tr data-depth="2" class="collapse level2" style="display: none;">
        <td>Item 3</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse level1" style="display: none;">
        <td>Item 4</td>
        <td>123</td>
    </tr>
    <tr data-depth="0" class="expand collapsable level0">
        <td><span class="toggle collapse"></span>Item 5</td>
        <td>123</td>
    </tr>
    <tr data-depth="1" class="collapse collapsable level1" style="display: none;">
        <td>Item 6</td>
        <td>123</td>
    </tr>
</table>

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

Hover over the Div element for inline effect

Hello all, I am currently working on running a while loop from a database to show different records. The twist is that these records are displayed as images, which makes it tricky to customize using standard CSS. To work around this, I'm implementing ...

Using ASP.Net MVC to link visible controls triggered by jQuery actions to the corresponding web model

I am working on a DropDownList that is populated with countries. When the user selects US, I want to display a dropdown menu with US states. If the user picks CA, I need to show a dropdown with CA provinces; otherwise, display a TextBox. With jQuery, I am ...

The player clicks once and the game is played two times

Struggling with a coding issue here. I've got some code where you click on an image and if it can be moved to the next cell, it should move. function changecell(a){ var moved=false; if(a%3 !=0) { if(ij[a-1]==0) { moved=true; ...

Pause and then resume the submit() function after conducting an ajax validation

I recently posted a query [here] but unfortunately, I haven't received any answers yet. Here's what I am trying to accomplish and you can view my initial attempt at the provided link: User fills out form Prevent default form submission Check if ...

Is there a way to convert this JSON object into HTML table code?

I've been working on tweaking a code snippet I came across, but I'm struggling to get it to function the way I desire. Here is the current Javascript code: function JsonUtil() { /** * Given an object, * return its type as a string. ...

Managing PHP multiple follow-up options in HTML select fields

My goal is to design a form that includes multiple follow-up select fields. These fields will be populated from an array with 3 elements: ID, Name, and followingID. The followingID corresponds to an ID in the array, helping us determine the hierarchical la ...

How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with. The situation involves a function that takes another function as a parameter: var myfunc = (func_outer) => { return func_outer().func ...

Exploring Vue's feature of passing props and emitting events within nested components

Within my coding project, I am facing the challenge of properly implementing a parent component containing a form that includes a birthday component. This birthday component consists of two separate components within it. My task is to effectively pass prop ...

leveraging third party plugins to implement callbacks in TypeScript

When working with ajax calls in typical javascript, I have been using a specific pattern: myFunction() { var self = this; $.ajax({ // other options like url and stuff success: function () { self.someParsingFunction } } } In addition t ...

I require the box element within my section element to have a full-width layout

Looking at the code in the image, you can see that I am using MUI components. Within a section, there is a box containing navigation filter links. The red part represents the section, while the white inside is the navigation link bar. My goal is for this b ...

Discovering the XPath of an element

Can anyone help me locate the XPath for the hamburger navigation icon on the website , specifically in the upper left corner? I am developing a Python script using selenium and need it to be able to click this particular button. Here's what I have tr ...

Tips for horizontally aligning an item in a flexbox only when it wraps onto a new line

In my layout, I have a container that consists of text on the left and a button on the right. The challenge I'm facing is ensuring proper alignment when they are on the same line versus when the button wraps to a new line on smaller screens. Ideally, ...

Tips for dynamically assigning unique IDs to HTML form elements created within a JavaScript loop

let count = 0; while (count < 4) { $('#container').append("<div><input type='textbox' class ='left' id='left-${count}'/><input type='textbox' class ='right' id=' ...

Pass information from Vue JS v-for to a button when it is clicked

Just started learning Vue JS and encountered a small issue I'm currently looping through an array with a button inside the div I'm iterating over The goal is to grab the data of the selected item after clicking on the button For example, suppo ...

Master the art of filtering rows in an HTML table based on a select option when the mouse is clicked

I am trying to create a table that displays only the rows selected in a dropdown menu. Here is an example: If "All" is selected, the table should display all rows. If "2017" is selected, the table should display only the rows that have "2017" in the sec ...

The functionality of Jquery events is limited when it comes to interacting with HTML elements that

<li> <label>Book Title</label> <input type="text" name="book[1][title]" /> </li> <li> <label>Content</label> <textarea name="book[1][content]" ></textarea ...

Verify the placement within the text box

Are there methods available in JavaScript or any JavaScript framework to determine the position within a textbox? For example, being able to identify that figure 1 is at position 2 and figure 3 is at position 3. Figure 1 Figure 2 ...

Is it possible to make changes to local storage data without impacting the rest of the data set?

I am looking for a way to modify specific data in the local storage without affecting any other stored information. However, I have encountered an issue where editing values works correctly for the first three attempts, but on the fourth try, it seems to ...

What is the impact of memory on NodeJS performance?

Currently delving into a book on NodeJS, I stumbled upon an intriguing example: const express = require('express') const bodyParser = require('body-parser') const app = express() var tweets = [] app.listen('8000', '172 ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...