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

Encountering the error "TypeError: Unable to access property 'controls' of undefined" when utilizing formArray in Reactive forms

Hi there, I am currently working on creating a dynamic form using formArray in Angular. However, I have run into an issue with the error message "TypeError: Cannot read property 'controls' of undefined." import { Component, OnInit } from ' ...

Transform object into JSON format

Is there a way to transform an object into JSON and display it on an HTML page? let userInfo = { firstName: "O", lastName: "K", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2b44476b445b05484446">[ema ...

Unable to insert hyperlinks into table rows within a React application

A React function was created by me to display a table. This is how the table appears. It accepts JSON as a parameter: { "id": 1, "firstName": "Richard", "lastName": "Morrison", "number ...

Changing the mouse cursor dynamically with Angular programming

What is the recommended approach for changing the mouse cursor programmatically in Angular? For instance: HTML: <div [style.cursor]="cursorStyle">Content goes here</div> or <div [ngStyle]="{ 'cursor': cursorStyle ...

Exploring how to replicate background-size: cover with a center position using HTML5's <video> tag

Looking to replicate the effect of background-size: cover on a <video> element. I was able to achieve this with the code below: <video id="videobackground" autoplay="true" loop="true"> <source src="BackgroundFinal2.mp4" type="video/mp4" ...

Display Quantity of Current Website Visitors

Similar Question: how to track website visitors using java script or php I am looking to retrieve the current number of viewers on a webpage that has an embedded stream. Is there a method to accomplish this utilizing PHP and AJAX, in order to display ...

Interaction between index file and module instance

As I develop a computer system, I have divided it into various smaller components. My experience in software development has taught me the value of keeping systems compact and focused. To achieve this, I am creating modules that perform specific function ...

Modify the divs in two separate occasions when submitting different forms

Within my form, I have radio buttons located inside div1, a captcha code to be solved in div2, and additional content in div3. My goal is to have div1 replaced by div2 when a radio button is checked and submitted. Then, after completing the captcha in div2 ...

Is there a method to verify the consumability of an API without having to make a direct request to it?

I'm working on an idle timer feature where the API will be called to update data once the timer runs out. How can I check if the API is still usable without actually sending a request? ...

The unrevealed node that is requesting the module is leading to an undefined outcome

I'm facing an issue where I need to import var server = require('../../index.js'); in my foo-dao.js file. This is necessary for accessing a hapi server plugin without passing it through the hapi request object from controller to dao. The pr ...

Rzslider not functioning properly due to CSS issues

I am facing an issue where rzslider is not appearing in my app. However, when I copy the code to an online editor, it works perfectly fine. Below is the code snippet: var app = angular.module('rzSliderDemo', ['rzModule', 'ui.boo ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

Having trouble getting CSS media query to work in my Rails mailer template

Is it true that media queries do not work in email templates? I have a simple test template and a query BUT can't seem to get it to function properly. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DT ...

The AreaChart in Google is displaying incorrect dates on the axis

I have encountered an issue that I am struggling to resolve. I am in the process of creating a Google Area Chart using a JSON response from a server, specifically with date type columns. Below is the JSON data obtained from the server (copy/paste), organi ...

Python code to locate images within HTML source code

Searching for images in an html source code can be tricky. I prefer using regex over the html.parser method, but I'm open to learning if you can explain it simply like you would to a child. I wish I could use beautifulsoup, but mastering the hard way ...

Utilizing jQuery to assign a value to a SPAN tag

In my code, there is an element with the following syntax: <span id="userName.errors" class="errors">Enter Your User Name </span>. I am interested in utilizing jQuery to delete either the text 'Enter Your User Name' or any element tha ...

I am in search of a specialized 3D camera with a unique effect

I am seeking assistance with animating a camera to replicate or closely resemble the effect seen in this demo: Any help would be greatly appreciated. ...

Enable users to provide ratings ranging from 0.5 up to 5

I recently created a rating component that allows users to rate on a scale from 0 to 4.5, with increments of 0.5, which is causing unexpected behavior. I actually want users to be able to rate from 0.5 to 5 instead. How can I achieve this adjustment? Below ...

Unraveling a Java String with HTML elements into a JsonObject: Step-by-step Guide

Hey there, I have a Java String that was received from an HTTP request and it looks like this: {SubRefNumber:"3243 ",QBType:"-----",Question:"<p><img title="format.jpg" src="data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."></img></p>"} ...