Customizing Your Accordion Group Code for Maximum Impact

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var active = document.querySelector(".accordion.active");
    if (active && active != this) {
      active.classList.remove("active");
      active.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  }
}

var accd = document.getElementsByClassName("accordion-deep");
var j;

for (j = 0; j < acd.length; j++) {
  acc[j].onclick = function() {
    var activeDeep = document.querySelector(".accordion-deep.active");
    if (activeDeep && activeDeep != this) {
      activeDeep.classList.remove("active-deep");
      activeDeep.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active-deep");
    this.nextElementSibling.classList.toggle("show");
  }
}
<button class="accordion">Section 1</button>
<div id="foo" class="panel">
<button class="accordion-deep">Section 1</button>
<div id="foo" class="panel-deep">
  <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>
</div>

I came across this code snippet in a forum and it has been working well for me. However, I encountered an issue when trying to add another accordion into section 1. Currently, the section closes whenever I click on a deeper accordion panel. I attempted to create another variable for the deeper accordion without success.

CSS: toggle accordion panel?

Answer №1

It seems like you may have borrowed code from another example since you didn't provide the CSS. I've made some adjustments to your code, and it's functioning properly now.

Prior to that, there were syntax errors in your code, such as:

this.classList.toggle("active-depp");

should be

this.classList.toggle("active-deep");

Additionally, all instances of acc should be changed to accd in the second function. However, the most crucial aspect is duplicating the CSS for both accordion-deep and panel-deep. For instance,

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    var active = document.querySelector(".accordion.active");
    if (active && active != this) {
      active.classList.remove("active");
      active.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active");
    this.nextElementSibling.classList.toggle("show");
  }
}

var accd = document.getElementsByClassName("accordion-deep");
var i;

for (i = 0; i < accd.length; i++) {
  accd[i].onclick = function() {
    var active = document.querySelector(".accordion-deep.active");
    if (active && active != this) {
      active.classList.remove("active-deep");
      active.nextElementSibling.classList.remove("show");
    }
    this.classList.toggle("active-deep");
    this.nextElementSibling.classList.toggle("show");
  }
}
button.accordion, button.accordion-deep {
background-color:#CBF1F5;

    color: #444;
    cursor: pointer;
    padding: 18px;
    width: 100%;
    border:solid 1px #3CF;
    text-align: left;
    outline: none;
    font-size: 18px;
    transition: 0.4s;
font-weight:600;
}

button.accordion.active, button.accordion-deep.active, button.accordion:hover, button.accordion-deep:hover {
    background-color: #E1F7FB;
}

button.accordion:after, button.accordion-deep:after {
    content: '\25bc';
    font-size: 13px;
    color: #777;
    float: right;
    margin-left: 5px;
}

button.accordion.active:after, button.accordion-deep.active:after {
    content: "\25b2";
color:#FFF;

}

.panel, .panel-deep {
    padding: 0 18px;
    background-color: white;
    max-height: 0;
    overflow: hidden;
    transition: 0.6s ease-in-out;
    opacity: 0;
}

.panel.show, .panel-deep.show {
    opacity: 1;
    max-height: 500px;  
}

.panel.hide, .panel-deep.hide {
    opacity: 0;
    height: 0;  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="accordion">Section 1</button>
<div id="foo" class="panel">
<button class="accordion-deep">Section 1</button>
<div id="foo" class="panel-deep">
  <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>
</div>

I hope this explanation helps.

EDIT : With this workaround, you can go one-level deep. But if you want to go deeper, copying code each time isn't an elegant solution.

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 component failing to update after state change

The layout is not displaying correctly when the state of page changes. Whenever I click on a category link, it verifies if the link exists in the category list. Then, it should update the page state to 'category'. Similarly, clicking on a recipe ...

In Java, the output of jsExecuteScript returns null, whereas in the browser console, it returns a String value

While running a script in the console of the browser on the aforementioned page, I encountered the following: document.querySelector('.subscribe_form input').value The placeholder value displayed was "Enter your email address." However, when at ...

Is it jQuery - Regarding the naming convention, should we choose a selector or an

I feel like this question might sound silly, but I can't seem to find a clear answer and it's starting to drive me crazy. Do all selectors passed to the jQuery constructor count as elements? Elements in the Document Object Model (DOM) include H ...

Automatic Opening and Closing of Bootstrap Modal

function toggleModals(hideModal, showModal) { console.log(hideModal); console.log(showModal); $(hideModal).modal('hide').on('hidden.bs.modal',function () { $(showModal).modal('show' ...

The issue arises when trying to apply CSS and minified JavaScript after adding new data in jQuery Mobile

I am having an issue with adding data and displaying it on a list. The problem arises when I add data through AJAX. In the success function, after showing the alert "successfully added", I used location.reload(), which takes me to the homepage (div tag dat ...

Transforming Bootstrap's navbar into a sleek side bar

As a Bootstrap 3 user, I am looking to implement a hidden sidebar that appears from left to right on click, similar to those seen in mobile apps. I have created a navbar using Bootstrap which transforms into a collapsible icon on smaller devices. Clicking ...

Insert within a canvas

Although there is a previous inquiry on this topic, it appears to be outdated. Despite searching through dartlang's resources and conducting online research, I have yet to find a solution to the issue at hand. document.onPaste.listen((e) { ...

Creating my initial React component/application, encountering problems with axios returning repetitive responses

Here is my React component: import './App.css'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faQuoteLeft } from '@fortawesome/free-solid-svg-icons'; import { faTwitter } from '@fortawesome/fr ...

Are there any drawbacks to utilizing data attributes for modifying content through JavaScript?

On my journey of developing a basic web app, I am faced with the challenge of updating data displayed on the screen based on certain events or conditions. The data is spread across various locations and embedded in completely different markup structures. I ...

Tips on temporarily halting frisby.js scripts while executing a sequence of API calls

I am looking to experiment with session timeout using Frisby.js. My plan is to first test the login API and then call another API to confirm that the user is logged in. Next, I want to configure frisby.js to wait for 20 minutes for the session to expire ...

php ajax access issue

Recently I've been encountering an issue where I am unable to access my php file using the $.ajax() function. Every time I make the call, I receive a jqXHR status of 0. Here is the code snippet that I am working with: Function with $.ajax() call: fu ...

Duplicating nested mapping in a React element

Struggling with mapping data in order to display it correctly. I have removed a large portion of the data, but the general structure remains intact: { "userData":[ { "name":"something", "job&quo ...

Understanding the distinctions among variables in typescript

Can someone explain the difference in Typescript between "!option" and "option"? It seems like they are not equivalent. const limit = !options.limit || options.limit === NaN ? 0 : options.limit ...

Sending emails to multiple recipients with different content using Nodemailer

I have been working on a method to send emails to multiple recipients while also passing the user attribute, which contains the name of the recipient, to the html template. (I AM UTILIZING NODEMAILER as a nodejs module) My current code looks like this: S ...

Javascript Losing focus

Upon creating a basic test page, I encountered an issue when tabbing through it in Internet Explorer. Initially, all the links are accessible with the tab key. However, upon attempting to tab through them for a second time, the focus cycles through the add ...

Configuring the space beneath a multi-line text with a bottom border distance or shadow

I am looking to add a bottom border with less spacing than default for specific text, creating a look similar to this image: https://i.sstatic.net/sCQii.png Unfortunately, it seems the border property cannot achieve this effect. I am experimenting with t ...

jQuery Dialog interface endlessly scrolls to the top

While debugging code for a project, I came across the use of jquery UI Dialog for popups. However, there seems to be an issue where the page keeps scrolling to the top while the dialog remains stationary wherever it was opened. Below is the code snippet in ...

What strategies can be employed to maintain reliable datetime management for a reservation system operating in diverse time zones?

Looking at the big picture: An interesting scenario arises when a hotel owner specifies a time frame for booking reservations at a restaurant (5pm - 10pm). Along with this information, there is also a timezone provided to ensure that dates are displayed i ...

Creating flat images from a three-dimensional volume

Currently, I am working on generating real-time mock-ultrasound images using volumetric CT data. A unique aspect of this project is that the user can control the position of the probe, determining the plane they are viewing. My approach so far involves ex ...

Unable to open Node.js Interactive Window in Visual Studio Enterprise 2017

Having some trouble with NodeJS development in Visual Studio 2017 Enterprise. Whenever I attempt to open the NodeJS Interactive Window, an error message pops up like this: https://i.sstatic.net/c02jJ.png Tried uninstalling and reinstalling Node.js tools ...