Expanding and collapsing Javascript accordion when a new tab is opened

Is there a way to prevent previously opened accordions from remaining open when opening another accordion? Any help on fixing this issue would be greatly appreciated. Thank you!

let acc = document.getElementsByClassName('ac-btn');
let i;

for (i = 0; i < acc.length; i++) {
  acc[i].onclick = function() {
    this.classList.toggle('active-accardacon');
    this.classList.toggle('active-ac');
    this.nextElementSibling.classList.toggle('show');
  }
}
<div class="accardacons">
  <h2>Explanation of Steps</h2>

  <div class="ac">
    <button class='ac-btn'>How do our projects work?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text...</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>More details about the steps</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text...</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>Can you really trust us?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text...</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>What guarantees do you have for your work?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text...</p>
    </div>
  </div>

</div>

Answer №1

The toggleAccordion() function provided below enhances your current functionality by following these steps:

  • It toggles the respective classes for the clicked accordion's elements (the button and its next sibling <div>), which aligns with what you're already doing;
  • Furthermore, it searches for elements with those classes and removes the classes from each one except for the button that was just clicked or its adjacent <div>.

let acc = document.querySelectorAll('.ac-btn');

function toggleAccordion() {
  this.classList.toggle('active-accardacon');
  this.classList.toggle('active-ac');
  this.nextElementSibling.classList.toggle('show');
  this.closest('.accardacons').querySelectorAll('.active-accardacon, .show').forEach(element => {
    if (element !== this && element !== this.nextElementSibling) {
      element.classList.remove('active-accardacon', 'active-ac', 'show');
    }
  });
}

acc.forEach(button => {
  button.addEventListener('click', toggleAccordion);
});
<div class="accardacons">
  <h2>Description of Steps</h2>

  <div class="ac">
    <button class='ac-btn'>How do our projects operate?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text generated simply with no meaning in the printing industry and using graphic designers prints but newspapers and magazines in columns and lines as needed</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>More details on work stages</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text generated simply with no meaning in the printing industry and using graphic designers prints but newspapers and magazines in columns and lines as needed</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>Can you really trust us?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text generated simply with no meaning in the printing industry and using graphic designers prints but newspapers and magazines in columns and lines as needed</p>
    </div>
  </div>

  <div class="ac">
    <button class='ac-btn'>What guarantee do you have for your work?</button>
    <div class="read-more-ac">
      <p>Lorem ipsum dummy text generated simply with no meaning in the printing industry and using graphic designers prints but newspapers and magazines in columns and lines as needed</p>
    </div>
  </div>

</div>

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

What could be causing axios to not function properly when used with async/await in this particular scenario

I need to update the DoorState when a button is clicked. After sending a request to the API to change the DoorState, I then call another API to check the status of the robot. Even though the DoorState has been successfully changed, it seems that the chan ...

Developing a slideshow with PHP and JQuery

Attempting to create a simple manual slideshow where the user clicks "next" to advance to the next slide. I have over 50 images and want to display them in batches of 8. For example, the first batch of 8 will be shown initially, then the user can click "ne ...

Issues arise when incorporating an iframe into a responsive website without the use of CSS styling

Having trouble with my site's iframes. Created animated banners using Bannersnack and embedded them, but the images always appear optimized for mobile, even on desktop. View the site here: The image at the bottom scales correctly, but not the animat ...

Show a popover within a parent div that has limited visible space due to its hidden overflow

Struggling with AngularJS, I can't seem to find a simple solution for this problem. In my code, there's a div element with the overflow: hidden property set due to an internal scrollbar. Inside this div, there's a dropdown menu that is trigg ...

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The server is unable to process the request sent by the browser or proxy. This error occurred in a Flask web application

Can someone guide me on troubleshooting this issue in Flask? I am still learning. Server running at (Press CTRL+C to exit) 127.0.0.1 - - [26/Jul/2020 11:19:45] "GET /predict HTTP/1.1" 500 - Traceback (most recent call last): raise exceptions. ...

Having trouble importing from the public folder in CSS with Create React App?

While working on a project initialized with Create React App, in the public folder there is an assets directory containing a file named logo512.jpg. When I use this file in a component like so: <div> <img src='/assets/logo512.jpg'/& ...

Tips on wrapping div elements while maintaining equal width in different screen sizes using @media queries

Does anyone have a solution for wrapping divs using @media screen while maintaining equal width on all divs? I've tried using float and inline-block, but can't seem to achieve consistent justified widths. While table-cells maintain equal field wi ...

Gather keyboard information continuously

Currently working with Angular 10 and attempting to capture window:keyup events over a specific period using RXJS. So far, I've been facing some challenges in achieving the desired outcome. Essentially, my goal is to input data and submit the request ...

The display of the expected outcome for the Three.js global heightmap is not appearing as intended

After discovering a global 4k height map online, I was eager to create a model of Earth using it. Fortunately, I stumbled upon an open-source script that promised to do just that. function createGeometryFromMap() { var depth = 512; var width = 512; ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

How can I prevent my JSON object from serializing .NET nulls as "null" for object members?

I am currently utilizing WebMethods to retrieve an array of a custom class. When this array is returned from a Jquery .ajax call, it gets serialized into a JSON object that can be utilized with Javascript in my ASP.NET application. The issue I am facing is ...

Utilizing React Views in an Express Environment

I am struggling to find a simple example that demonstrates how to connect an Express.js route to render a React view. This is what I have tried so far. +-- app.js +-- config | +-- server.js +-- routes | +-- index.js +-- views | +-- index.html app. ...

The operating system MacOS requests permission from the parent Node process rather than the child process

When using the child_process module, I encountered a situation where MacOS prompts for permissions for the parent process instead of the spawned child. For instance, running the code below in the terminal results in MacOS asking for permission for "Termina ...

assign a role to a discord.js user using the role stored in the client class variable

Is there a way to dynamically assign a role to a user using the client variable const client = new Client({ intents: [GatewayIntentBits.Guilds] }); instead of through an interaction? The user's role needs to be updated when a 3rd party request is rec ...

Tips for saving a JavaScript function in JSON format

Looking to store a JS object in Local Storage for future reference, but struggling to convert it to a string. Here’s the code: JSON.stringify({ x: 10, y: function (input) { return input; } }) As a result, I get: "{"x":10}" Any su ...

Tips for creating a dynamic design for an Inputfield when it is in use

Imagine if the background color is red and I want the input text field to be red as well. However, when you click inside the input field to type, it should turn into a regular text field. And of course, when you are not actively typing in the input field, ...

What is the recommended approach for linking CSS files when utilizing ASP.NET URL routing?

Within my URL routing setup, I have a master page content template that references a stylesheet on the destination page: <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"> <link href="css/actionmenu.css" rel="stylesheet" t ...

What are the steps to correctly shut down an ExpressJS server?

I am facing a challenge with my ExpressJs (version 4.X) server - I need to ensure it is stopped correctly. Given that some requests on the server may take a long time to complete (1-2 seconds), I want to reject new connections and wait for all ongoing req ...

Changing the slider based on the format of the price and user input value

Is there a specific place where I should use the .toFixed(2) method to ensure fixed formatting for my range slider output? For example, transforming 1.9 to 1.90 or 2 to 2.00. Additionally, is it feasible to have an input field where the user enters a pri ...

Script written in PHP to retrieve text from a website, then translate and save it onto a local storage

Is there a way to save text from a website to a local file? The script should perform the following actions: Visit this website (fake site) http://website/webtv/secure?url=http://streamserver.net/channel/channel.m3u8**&TIMESTAMP** where TIMESTAMP ...