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:

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

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

Mastering the Material-UI Grid in SPAs: Conquering the Negative Margin Dilemma

While attempting to build a single page application (SPA), I've encountered an issue with using the Grid component from material-ui. Normally, I rely heavily on the Grid, but in this new project, something seems amiss. The current problem is evident ...

Inconsistency in date serialization using JSON.stringify across various web browsers

I've written this snippet in an HTML file: alert(JSON.stringify(new Date())); To cater to older browsers lacking JSON.stringify(), I've included the latest json2.js (2009-09-29 version) along with jquery-1.3.2.js. In modern browsers with native ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

Does the media query max-width refer to the size of the viewport or the size of the window?

Can someone clarify whether the max-width in a media query is based on the viewport size or window size? For instance, consider this media query: @media screen and (max-width: 360px){} Would this media query be activated when the viewport reaches 360px ...

The complexity of JQuery's design has left many puzzled

I am new to using Jquery and I have come to the following realizations: Every selector in Jquery always returns a wrapped list of items, which can be: An empty list A list with a single element A list with multiple elements Chained functions operate o ...

CSS-exclusive dropdown menu elements peeking out

I have been working on a CSS-only drop-down menu and I am encountering an issue where other content seems to be showing through. Despite my efforts, I can't figure out why this is happening. If you would like to take a look, here is the link: http:// ...

Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) { var tipPercent; if (bill < 50 ) { tipPercent = .20; } else if (bill >= 50 && bill < 200){ tipPercent = .15; } else { tipPercent = .10; } return tipPercent * bill; } var bills = ...

Avoiding Memory Leaks and Managing JS Heap Size While Polling Large Amounts of Data Every 5 Seconds with Vuex

I'm currently working on a Vue application that utilizes Vuex for state management. Within this application, I have several store modules set up at the root level. Periodically, every 5 seconds, I retrieve a large amount of data and update the store s ...

Crushing jQuery's Sortable/Droppable

Having a little issue here. I want to be able to toggle the sortable plugin's behavior by clicking a button - basically switching between sort mode and view mode. I've attempted to achieve this with the following code: function enterSortMode(){ ...

Retrieve the most recent information from the database based on a specific column

Is there a way to retrieve only the most recent row from each category in the database? Example Database: Table name: Colors id category timestamp 1 yellow 14/2/2014 2 blue 13/2/2014 3 red 14/2/2014 4 yellow 13/2/2014 5 blue 11/2/2014 ...

Tips on obtaining the response (in JSON format) in your console when accessing a URL

Can someone help me integrate this code into my project and guide me on how to proceed with it? function validate() { var un = document.loginscreen.uname.value; var pw = document.loginscreen.psw.value; var username = "John_Smith"; var passw ...

Node Webkit: No visible content?

Recently, I decided to explore Node-Webkit and encountered an issue. Despite coding the script below, nothing seems to appear on the screen and the file I intended to create remains missing. Even after installing npm for fs and os modules, I still face no ...

Determining the final value of the last handle in a jQuery UI slider with multiple sliders present

I need help retrieving the first and last handle values from a jQuery UI range slider when there are multiple sliders on the page. Currently, my code is set up to grab the last value from the last slider's last handle. I attempted to address this by u ...

Position an element in the middle of the range between the tallest and shortest characters

Is there a way to vertically center an element between the tallest and shortest characters of another element (preferably using just CSS, but JavaScript is also acceptable)? I want it to be aligned with the actual text content rather than the line height, ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

Error in Chrome: Text container's height is not fully extended to 100%

I'm encountering an issue with achieving 100% height on a child container in Google Chrome, although it works perfectly fine on Firefox. Here is the URL: http://linco.com.py/beta/multiplaza/cartelera.php The styling for the main container is as fol ...

Store additional data with the visitor ID WEB in Fingerprint JS V3

After browsing through similar questions, I couldn't find a solution that fits my needs. Basically, I have a website where a random emoji is generated and stored in local storage. However, this method is not effective as users can easily delete their ...

The jQuery fadeOut function modifies or erases the window hash

While troubleshooting my website, I discovered the following: /* SOME my-web.com/index/#hash HERE... */ me.slides.eq(me.curID).fadeOut(me.options.fade.interval, me.options.fade.easing, function(){ /* HERE HASH IS CLEARED: my-web.com/index/# * ...

The jQuery html function may encounter issues when used in Chrome browser

Can someone help me figure out why this code isn't functioning properly in Chrome, even though it works fine in Safari? I've been searching for a solution but haven't had any luck! jQuery.noConflict(); jQuery(document).ready(function() { ...