JavaScript button for displaying and hiding all content in one click

I came across a tutorial on W3Schools that showed how to create collapsibles, and I thought it would be great to have buttons that could expand or collapse all at once. I've been trying to implement this feature using the code provided in the tutorial but seem to be struggling with getting two working buttons. Here is the snippet of code I am currently working with.

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";
    } 
  });
}
<style>
.collapsible {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}

.active, .collapsible:hover {
    background-color: #555;
}

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

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

.content {
    padding: 0 18px;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    background-color: #f1f1f1;
}
</style>
<button class="collapsible">Open Section 2</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="collapsible">Open Section 3</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>

Answer №1

Is this the outcome you're aiming for? Using jQuery, here's an example that you can customize to suit your needs.

$('.item').on('click', '.header', function(){
  $('.item').removeClass('show')
  $(this).parent().toggleClass('show')
})
.item {
  border: 1px solid #ddd;
  margin: 5px;
}
.header {
  padding: 10px;
  cursor: pointer;
}
.content {
  height: 0;
  overflow: hidden;
  transition: all 0.3s ease;
  border-top: 1px solid #ddd;
}
.item.show .content {
  height: auto;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<section class='item'>
  <div class='header'>Item 1</div>
  <div class='content'>Content 1</div>
</section>

<section class='item'>
  <div class='header'>Item 1</div>
  <div class='content'>Content 2</div>
</section>

Answer №2

This is the extended version of your code.

I believe this fulfills your request

var elements = document.getElementsByClassName("collapsible");
var j;

for (j = 0; j < elements.length; j++) 
{
  elements[j].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";
    } 
  });
}

var expAllButton = document.getElementById('expAll');
    expAllButton.addEventListener('click', function() {
      expandDetails(true);
    }, false);

    var collAllButton = document.getElementById('collAll');
    collAllButton.addEventListener('click', function() {
      expandDetails(false);
    }, false);

    function expandDetails(y) {
      var infoSections = document.getElementsByClassName("collapsible");
      Array.from(infoSections).forEach(span => {
        var content = span.nextElementSibling;
        var conditionCheck;
        var resultValue;
        switch (y) {
          case false:
            conditionCheck=content.style.maxHeight == content.scrollHeight + "px";
            resultValue=null;
            break;
          case true:
            conditionCheck=content.style.maxHeight == null || content.style.maxHeight == "";
            resultValue=content.scrollHeight + "px";
            break;
          default:
        }
        if (conditionCheck) {
          span.classList.toggle("active");
          content.style.maxHeight = resultValue;
        }
      });
    }
<style>
.collapsible {
    background-color: #777;
    color: white;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border: none;
    text-align: left;
    outline: none;
    font-size: 15px;
}

.active, .collapsible:hover {
    background-color: #555;
}

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

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

.content {
    padding: 0 18px;
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
    background-color: #f1f1f1;
}
</style>
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <title></title>

<a href='#8' id='expAll'>Expand All</a>
<a href='#9' id='collAll'>Collapse All<br></a>

</head>

<body>
<button class="collapsible">Open Section 2</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
<button class="collapsible">Open Section 3</button>
<div class="content">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</body>
</html>

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

I've been struggling with this javascript error for three days, how can I finally resolve it?

Currently developing a website using react js, but encountering an error every time I try to push to my github repository. Run npm run lint npm run lint shell: /bin/bash -e {0} <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail= ...

What is the best way to retrieve a GWT textbox value using Selenium WebDriver?

I'm currently testing my GWT application with selenium, and the HTML generated by GWT Textbox appears like this: <input type="text" class="gwt-TextBox" > Even though there's no value visible in the code above, I can see text in the UI. Is ...

Issue with collecting data in Meteor Collection

After making some edits to another file and increasing the complexity of my application, a tracker function that was previously working fine is now experiencing issues. It is no longer returning any data for vrLoan fundingData This is a snippet of my c ...

Animating with React using the animationDelay style does not produce the desired effect

Is there a way to apply an animation to each letter in a word individually when hovering over the word? I want the animation to affect each letter with an increasing delay, rather than all at once. For example, if scaling each letter by 1.1 is the animatio ...

What is the best way to upload an object in React using fetch and form-data?

Currently, I am facing an issue where I need to send a file to my express app as the backend. The problem lies in the fact that my body is being sent as type application/json, but I actually want to send it as form-data so that I can later upload this file ...

Tips for effectively downsizing an HTML Canvas to achieve high-quality images

Introduction I am currently facing issues with blurry visuals in my canvas animation, especially on devices with high pixel densities like mobile and retina screens. In order to address this problem, I have researched canvas down-scaling techniques and f ...

Send the Children prop to the React Memo component

Currently, I am in the stage of enhancing a set of React SFC components by utilizing React.memo. The majority of these components have children and the project incorporates TypeScript. I had a notion that memo components do not support children when I en ...

Effortless Ways to Automatically Accept SSL Certificates in Chrome

It has been quite some time that I have been attempting to find a way to automatically accept SSL certificates. Unfortunately, I haven't had any success yet. The scenario is this: I am working on selenium tests and every time I run the test on Chrome, ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

JavaFX text label does not adjust its font according to the CSS file

In my FXML file, the structure is as follows: ... <BorderPane id="header"> <right> <Label styleClass="title" text="A Label" /> </right> </BorderPane> ... I also have a CSS file with the following content: #h ...

The ref.on() method fails to trigger a response from a function, despite producing the intended outcome

I've been working on developing an app called workspace. I previously asked a question, but I've made more additions to the features now. One of the new features is a remarks system. After experimenting with different versions of my code, the ver ...

Enhance the appearance of your Dojo TabContainer when viewing in Internet Explorer

Firefox seems to handle the following code without any issues: < div style="position:absolute;top:0px;margin-top:60px;bottom:0px;width:100%"> < div id="mainTabContainer" dojoType="dijit.layout.TabContainer" style="width:100%;height:100%"> {% fo ...

Nuxt and Express server are unable to receive API requests when in production mode and the /dist directory

My Nuxt app is running smoothly on my local server, with all API requests working perfectly using the serverMiddleware property in nuxt.config.js. However, when I run yarn generate, the path to the API server gets lost and no data is loaded. Here are some ...

What are the capabilities of Ajax when it comes to utilizing select controls in J

Is there a way to trigger an ajax call when a select control value is clicked? The onChange event doesn't seem to work for me in this case :( This is what I have tried so far: JAVASCRIPT: <script> function swapContent(cv) { $("#myDiv"). ...

What is the process for extracting specific text from a web page source using Python with Selenium?

The following is the HTML source code: <div class="dropdown-popup"> <a href="/integrations/sources/" class="dropdown-item">Sources</a> <a href="/integrations/destinations/" cla ...

What are some effective methods for selectively handling batches of 5-20k document inputs when adding them to a collection containing up to one million documents using MongoDB and Mongoose?

My MMO census and character stats tracking application receives input batches containing up to 5-20k documents per user, which need to be aggregated into the database. I have specific criteria to determine whether a document from the input already exists i ...

Utilizing the powerful combination of TailwindCSS and Next.js Image to achieve a full height display with

Trying to utilize the Next.js' <Image> component with the layout=fill setting, I created a relative div housing the Image tag. However, I am looking for a way to set the height based on the Image's height. Came across this example, but the ...

Ensuring Valid Submission: Utilizing Jquery for a Straightforward Form Submission with 'Alajax'

After searching for a straightforward JQuery plugin to streamline the process of submitting forms via Ajax, I stumbled upon Alajax. I found it quite useful as it seamlessly integrates into standard HTML forms and handles all the necessary tasks. However, I ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...