Dynamic collapsible containers

I discovered a useful feature on w3schools for collapsing elements: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_collapsible_symbol

However, I would like to reverse it so that all elements are initially shown when the page loads, and then use this feature to toggle between visible and hidden states.

Below is the code I currently have:

<style>
.collapsible {
  background-color: #777;
  color: white;
  cursor: pointer;
  padding: 5px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 12px;
}

.collapsible:after {
  content: '\002B';
  color: white;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}

.collapsible.active:after {
  content: "\2212";
}

.content {
  padding: 0 20px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}
</style>
<script>
    $(document).ready(function() {
        var coll = document.getElementsByClassName("collapsible");
        var i;

        for (i = 0; i < coll.length; i++) {
          coll[i].addEventListener("click", function() {
            this.classList.toggle("active");
            var content = this.nextElementSibling;
            if (content.style.maxHeight){
              content.style.maxHeight = null; 
            } else {
              content.style.maxHeight = content.scrollHeight + "px";
            } 
          });
        }
    });
</script>

You can see an example of this implementation here: https://jsfiddle.net/g50v4cL2/

My goal is to have the elements shown as depicted in the image below when the page loads:

https://i.sstatic.net/ZuvG4.png

Afterward, I should be able to collapse and expand them at will. Can anyone assist me with achieving this?

Thank you for your help.

Answer №1

There are numerous methods to achieve this, but in this particular scenario, I opted to retain the existing structure with minimal modifications. Simply add the active class to your elements and adjust your JavaScript code as follows:

        var coll = document.getElementsByClassName("collapsible");
        var i;

        const adjustContentHeight = (content) => {
          if (content.style.maxHeight){
              content.style.maxHeight = null; 
          } else {
              content.style.maxHeight = content.scrollHeight + "px";
          }
        }

        for (i = 0; i < coll.length; i++) {
          adjustContentHeight(coll[i].nextElementSibling);
    
          coll[i].addEventListener("click", function() {
            this.classList.toggle("active");
            adjustContentHeight(this.nextElementSibling);
          }); 
        }
.collapsible {
  background-color: #777;
  color: white;
  cursor: pointer;
  padding: 5px;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 12px;
}

.collapsible:after {
  content: '\002B';
  color: white;
  font-weight: bold;
  float: right;
  margin-left: 5px;
}

.collapsible.active:after {
  content: "\2212";
}

.content {
  padding: 0 20px;
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.2s ease-out;
  background-color: #f1f1f1;
}
<button class='collapsible active'>Test1</button>
<div class='content'>
<label><input type = 'checkbox' value = 'value1'/> value1</label>
<label><input type = 'checkbox' value = 'value2'/> value2</label>
<label><input type = 'checkbox' value = 'value3'/> value3</label>
<label><input type = 'checkbox' value = 'value4'/> value4</label>
</div>

<button class='collapsible active'>Test2</button>
<div class='content'>
<label><input type = 'checkbox'  value = 'value5'/> value5</label>
<label><input type = 'checkbox'  value = 'value6'/> value6</label>
<label><input type = 'checkbox'  value = 'value7'/> value7</label>
</div>

If you prefer not to have the transition effect at the start, you can eliminate the transition property from the CSS and introduce it in the JavaScript after implementing this code.

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

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

Dealing with bulkWrites in Mongoose and MongoDB: how to handle cast errors with finesse

When importing data into my app's database using MongoDB's bulkWrite operation, I encounter a challenge. The data may contain errors as it comes from an external source. To maintain the integrity of my data, I need to update my collection while s ...

Gradually blend the section of the picture with an image banner after 20 seconds

I have a background image that rotates every 20 seconds, fading in and out. The images consist of a logo at the top-left corner and a person image at the right side from top to bottom. However, I want only the person image to fade in and out while keeping ...

The subscription for the second Observable in RxJS concatMap is triggered individually

I am currently developing an Angular 6 application. I want the app to display a loading animation whenever there is a change in the route or if there are any pending HTTP requests. To achieve this, I have set up two Observables as follows: For httpPendingR ...

django, the X-CSRFToken in the request header is improperly configured

Essentially, I have managed to successfully send a CSRF token to the frontend and store it in the cookie section of the application tab within the developer console of the browser with this code: @method_decorator(ensure_csrf_cookie) def get(self, ...

Show a pop-up notification for a compact disc

Received a CD containing various tutorials created in HTML. I am looking to have a browser window open with specific parameters, such as no toolbars and fixed width/height, to properly display the content. Using window.open with multiple parameters trigge ...

Notification for Unsuccessful Login Attempt on the Client Side

In my node.js project, I have implemented a login form that sends data to the server.js file as URL parameters. When the sent data is verified against registered users, the client is successfully logged in. However, I am facing an issue on how to notify th ...

AngularJS implementation for a confirmation dialog with data

I need help creating a confirmation dialog box for user action verification. Here's the situation: I have a table with multiple events, and users can choose to delete an event. This is how the table is structured: <tbody> <tr ng-repeat= ...

Retrieve the origin of the copied text

While working on a Vue application, I'm curious to know if it's possible to access the source of pasted text. For example, whether the pasted text originated from your own application, Word, or Notepad? I attempted the code below but was unable ...

Conceal elements on smaller screens using the Bootstrap 5 grid system

I'm facing a design issue with my layout - it looks perfect on larger screens but when viewed on mobile devices, the columns stack vertically instead of horizontally. Essentially, I want to hide the first and second last column on small screens and r ...

The v-model in the Vue data() object input is not functioning properly and requires a page refresh to work correctly

Explaining this situation is quite challenging, so I created a video to demonstrate what's happening: https://www.youtube.com/watch?v=md0FWeRhVkE To break it down: A new account can be created by a user. Upon creation, the user is automatically log ...

Capture Video on iOS devices using the MediaRecorder API and display it using HTML5 Video Player

Issue: I am facing an issue where I cannot record video or get a video stream from the camera on iOS through my Angular web application built using ng build. Investigation: In my investigation, I explored various websites that discuss Apple iOS features ...

Trouble with Chrome's CSS making table cell display as block

After searching, I stumbled upon this question that appeared to have the solution I needed. Surprisingly, even when using chrome 32.0.1700.102, the fiddle provided in the first answer worked perfectly for me. However, when I copied the HTML code into a ne ...

Please ensure all three of the last checkboxes are ticked before finalizing submission

Here is the list of checkboxes for my PHP form. I am trying to figure out how to write a script that will only allow the form to be submitted if the last three checkboxes are checked. I have tried looking at similar questions but haven't found the sol ...

create new Exception( "Invalid syntax, expression not recognized: " msg );

Can someone assist me in identifying the issue at hand? Error: There seems to be a syntax error, and the expression #save_property_#{result.id} is unrecognized. throw new Error( "Syntax error, unrecognized expression: " msg ); Here is the c ...

Webpack loaders or plugins: understanding the distinction

Can you explain the distinction between loaders and plugins in webpack? I found on the documentation for plugins that it states: Plugins are used to incorporate extra functionalities usually related to bundles within webpack. While I understand that b ...

Adding a new key-value pair to a JSON data structure

Here is the JSON object that I am currently handling: { "name": "John Smith", "age": 32, "employed": true, "address": { "street": "701 First Ave.", "city": "Sunnyvale, CA 95125", "country": "United States" }, ...

Is it possible to stack images on top of each other on a webpage?

I'm looking to create a dress-up game website where users can click on different accessories to layer them on top of each other. It's a bit tricky to explain, but I've found some examples that demonstrate what I have in mind: This site is ...

Preventing Page Refresh when Button is Clicked in Angular

How can I prevent page reload when a button is clicked in Angular? I'm developing a quiz application in Angular where I fetch random questions and options from an API. When users select an option, the next question should appear without reloading the ...

The navigation bar and column layout is not functioning properly in Firefox

Hey there! I'm having a little issue with my website. When I view it in Chrome, everything looks perfect - the logo is left aligned at the top right and the testimonials section at the bottom has a nice 3 column layout. But when I try to open it in Fi ...