CSS implementation of a treeview with a dropdown submenu

I'm currently customizing an HTML tree view using CSS, and my goal is to have sublists smoothly slide down whenever a node is expanded.

Take a look at my streamlined index.html :

<!DOCTYPE html>
<html>

  <head>
    <script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body>
    <div class="node">
      Div-1
      <div class="children">
        <div class="node">
          Div-1-1
        </div>
      </div>
    </div>
    <div class="node">
      Div-2
    </div>
  </body>

</html>

Here's the script.js content :

$(document).ready(function() {
  $('.node').click(function(event) {
    $(event.target).toggleClass('expanded');
  });
});

And this is the style.css specific styling :

.node {
  border: solid 1px red;
}
.node > .children {
  border: solid 1px lightblue;
  overflow: hidden;
  padding-left: 10px;
  max-height: 0;
  transition: max-height .5s ease-in;
}
.node.expanded > .children {
  display: block;
  max-height: 50px;
}

The output (view on plunkr1) looks good BUT it's not just the sublist sliding down—it's the entire tree revealing the sublist.

To address this, I made changes by wrapping the "children" div as follows:

<body>
  <div class="node">
    Div-1
    <div class="childrenWrapper">
      <div class="children">
        <div class="node">
          Div-1-1
        </div>
      </div>
    </div>
  </div>
  <div class="node">
    Div-2
  </div>
</body>

Moreover, I adjusted the CSS like so:

.node {
  border: solid 1px red;
}
.node > .childrenWrapper {
  border: solid 1px lightblue;
  overflow: hidden;
  padding-left: 10px;
}
.node > .childrenWrapper > .children {
  transform: translateY(-100%);
  transition: transform .5s ease;
}
.node.expanded > .childrenWrapper > .children {
  transform: translateY(0);
}

Now with improvements in place (check out plunkr2), the sublist slides properly. Although there's an issue with the wrapped div maintaining the sublist size preventing a neat presentation.

I'm stuck on finding a resolution for this. Any suggestions?

Answer №1

Revise the CSS in the following manner:

.node > .childrenWrapper {
    transition:height .5s;
    height: 0;
}
.node.expanded > .childrenWrapper {
    height:auto;
}

Update the JS as shown below:

$(document).ready(function () {
    $('.node').click(function (event) {
        var $e = $(this),
            $childrenWrapper = $e.find('.childrenWrapper'),
            $children = $e.find('.children'),
            h = $e.is('.expanded') ? 0 : $children.height(); // target height based on whether it is expanded or not.
        $childrenWrapper.height(h); // setting height for childrenWrapper (observe css transition on .node > .childrenWrapper)
        $(this).toggleClass('expanded');
    });
});

See a demo here: https://jsfiddle.net/49te34wx/

By the way, changing

$(event.target).toggleClass('expanded');
to $(this).toggleClass('expanded'); simplifies 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

Something seems to be wrong with the Javascript functionality in ASP.NET

Returning to coding some .NET projects, I decided to experiment with JavaScript/jQuery. I've included my /js/myscript.js file and confirmed that it is loading when the page loads. Within my js file, there is only one call: alert('TEST'). ...

Having trouble with the Tailwind transition in my Next.js component

I'm facing an issue with the ease out transition not working as expected. I need the side to slide in from left to right with a duration of 500ms. Despite trying various solutions, I can't seem to figure out why it's not functioning properly ...

"Major issues arise as CSS3 Animation fails to function properly across all web

I have been experimenting with using a sprite and CSS3 animation to create a rollover effect. While it seems to be working in CODA 2, I'm encountering issues when testing in Mozilla, Chrome, Safari, and Opera as the animation fails to trigger. /*link ...

What could be the reason for the absence of this Javascript function in my attribute?

I have been working on an app using electron, and I have a function that successfully adds tabs to the app. The issue arises when I try to add tabs via JavaScript with the onclick attribute - they show up as expected but do not execute the code to hide and ...

What is the best way to display items within a table using React?

I'm just starting to learn React. Can someone show me how to use the "map" function to list elements from two different arrays in two columns? state = { dates: ["2000", "2001", "2002"], cases: ["1", "2", "3"] } render() { return ( <thea ...

extracting information online with python selenium web scraping

Having trouble retrieving the content in this location as it is showing up blank. Can someone please assist me? The element I am trying to capture is: Đã bán 74k/tháng Here is my code snippet: print(driver.find_elements(By.CSS_SELECTOR, "div.r ...

Having trouble with the menu toggle button on Bootstrap 4?

When using Bootstrap 4, the breadcrumb button may not function properly when the header becomes responsive. I have ensured that Bootstrap 4 CSS and JS are included in the project. Please assist me in resolving this issue. Code: .navbar { height:100 ...

Tips for integrating the AJAX response into a Sumo Select dropdown menu

I am currently using Sumoselect for my dropdowns, which can be found at . The dropdowns on my page are named as countries, state, and cities. The countries are shown in the dropdown, and based on the country selected, the corresponding state name should a ...

I'm having trouble getting the footer to stay at the bottom of my website

Struggling with positioning my footer at the bottom of my website, I've tried various solutions posted by others but they don't seem to work for me. I've experimented with different methods like using 'Bottom: 0;' or placing my fo ...

Passing a variable from jQuery using AJAX to an external PHP file

After discovering a PHP/jQuery/AJAX script with a textfield that sends user input to an external PHP script for storage in a MySQL database (), I realized that the user ID is missing from the process. $sql = "UPDATE customer SET comment = '$content&a ...

How to use CSS to make a child element's width automatically fill the width of its

Is there a way to make the child div info fill the parent div video-featured width while remaining absolute, allowing it to overlap the parent div without using a fixed width? <div class="video-featured col-md-4"> <div class="video"> < ...

placing additional containers at the bottom rather than on the right side

Hey there! I'm currently working on a simple website and I'm having trouble getting the duplicated form rows to appear aligned below the previous one. Here's what I have right now: var i = 0; var original = document.getElementById("dupl ...

Revamp the Side Navigation Feature to Identify the Currently Viewed Section of the Page

My website currently features a side navigation bar that dynamically updates based on the user's scroll position. When the user reaches a specific height, a class is added to a div in the sidebar, turning it orange and indicating which part of the pag ...

Pressing a button is a way to select a specific form

I'd like to create a clickable button that can direct users to the form section on the same page. <button type="button" class="btn btn-primary btn-sm"> Go to Form Section </button> ... <form id="form1"> <div class="form-g ...

Showcase text in a straight row by utilizing ng-repeat and bootstrap

My goal is to show each word on a new line, similar to how words are displayed in a hangman game. The words should be displayed as blanks. <body ng-init="models = [['H','a','p','p','y'],['X',& ...

"Exquisite Broth - What is the best way to extract images with a particular src attribute using web scraping

Recently, I embarked on a journey to learn webscraping and decided to take on the challenge of scraping Mangadex as my latest project. Any advice you can offer would be highly appreciated! My goal is to extract images by capturing the src attribute of an ...

What is the process for sending JavaScript with an Ajax request?

Working with ajax and javascript for the first time, I'm no expert in web development. Here is the code I've written and tested so far. I have a select div containing some options. <select id="month" onchange="refreshGraph()"> When an op ...

PHP is functioning properly, but no content is being displayed

I recently delved into coding and had to tackle a form that sends data through email using PHP. While the functionality of my form is working perfectly and I'm able to receive emails, I encountered an issue where the PHP page appears blank. Despite tr ...

Tips for assigning a preset value to a checkbox

Is there a simple way to set the default Checked value of this angular checkbox? <p class="card-text">Please let me know which public organizations have been notified.</p> <div for="stakeholders" class="custom-control custom-c ...

Basic CSS element placement

Visit my website here. There is a black video box under the product image that I want to align to the left. I tried to adjust the CSS but couldn't find anything causing the issue. When I move the video box above the Facebook button and align it to t ...