I require only one menu to be displayed in this user interface

This user interface was crafted by me and I am seeking the same functionality to be integrated into this design. I want only one menu to be open at a time, rather than having all of them open simultaneously.

Clicking on a button should open or close the current accordion. Additionally, if any other accordion is already open, it should automatically close when you attempt to open another one.

Kindly maintain the same transitioning effect.

var accordians = document.getElementsByClassName("accordion_btn");
for (var i = 0; i < accordians.length; i += 1) {
  accordians[i].onclick = function() {
    this.classList.toggle('arrowClass');
    var content = this.nextElementSibling;
    if (content.style.maxHeight) {
      // Accordion is open, needs to be closed
      content.style.maxHeight = null;
    } else {
      // Accordion is closed, needs to be open
      content.style.maxHeight = content.scrollHeight + "px";
    }
  }
}
body {
  display: grid;
  place-items: center;
}

.accordion_container {
  background-color: #efefef;
  padding: 10px;
  width: 500px;
  /*height: 400px;*/
  overflow: auto;
  border-radius: 3px;
  /* padding: 10px; */
  position: relative;
}
... (the rest of the CSS code remains same)
<div class="accordion_container">
  <div class="accordion_body">
    <div class="accordion_body_item">
...

Answer №1

By making some adjustments, you can achieve the desired outcome more efficiently. Simplifying the html and css code and incorporating newer JS ES6 syntax can enhance functionality and streamline development.

I have included annotations to highlight where modifications were made.

  // Utilize QuerySelector for toggle buttons
  const accordians = document.querySelectorAll(".accordion_btn");

  // Assign onclick handler in a loop
  accordians.forEach((element) => {
    element.onclick = (event) => {
      // Obtain trigger element and corresponding body
      const toggleButton = event.target;
      const accordianBody = toggleButton.nextElementSibling;

      // Retrieve list of open accordians
      const openAccordians = document.querySelectorAll(
        ".accordion_content.open"
      );
      // Get list of open accordians
      const toggleButtons = document.querySelectorAll(
        ".accordion_btn.arrowClass"
      );

      // Check if clicked accordian is already open
      if (accordianBody.classList.contains("open")) {
        accordianBody.classList.remove("open");
        toggleButton.classList.remove("arrowClass");
        return;
      }

      // Close other open accordians
      openAcccordians.forEach((item) => item.classList.remove("open"));
      toggleButtons.forEach((item) => item.classList.remove("arrowClass"));

      // Open the clicked accordion
      accordianBody.classList.add("open");
      toggleButton.classList.add("arrowClass");
    };
  });
  body {
    display: grid;
    place-items: center;
  }

  .accordion_container {
    background-color: #efefef;
    padding: 10px;
    width: 500px;
    /*height: 400px;*/
    overflow: auto;
    border-radius: 3px;
    /* padding: 10px; */
    position: relative;
  }

  // Adjusted CSS as needed

  /* Add open body state with css */

  /* Accordian Closed state */
<div class="accordion_container">
  <div class="accordion_body">
    <!-- Repeat structure for each accordion item -->
  </div>
</div>

Update: Corrected comment formatting in CSS section.

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

Leveraging jQuery, Ajax, and PHP for generating and organizing HTML blocks - requiring sound logic

I am in the process of developing a website that compares different products. I have implemented code that retrieves and scrapes data for comparison when a user performs a search. Right now, I am using an ajax request for each company (currently 6 compani ...

load specific div using jQuery AJAX

My question is quite straightforward - how can I use a jQuery AJAX command to retrieve a specific div? $.ajax({ url: "test.html", success: function(){ $(this).addClass("done"); } }); Is it possible to achieve this using the ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

JavaScript: Locate web addresses within a block of text and convert them into clickable hyper

How can we convert the following PHP code to JavaScript in order to replace URL links inside text blobs with HTML links? A jsfiddle has been initiated. <?php // The Regular Expression filter $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a- ...

Javascript toggle navigation with sliding and fading effects

Tap on the flower to reveal the menu. I have successfully implemented the animation for "process" fading in after the menu opens. However, I am struggling to reverse the animation when collapsing the menu. I want "process" to fade out before the menu close ...

Could someone provide clarification on this particular line of Apex code for me?

I'm completely new to Oracle Apex and I could use some guidance in understanding the code snippet I came across in a tutorial about app creation. After digging around, I suspect it might be JavaScript, but I'm not entirely certain. The scenario ...

Utilizing the If statement within AlertifyJS

Whenever I attempt to use an if statement in conjunction with Alertify, it doesn't seem to function properly. Could there be an error in my approach? var question = alertify.prompt("What is your name?", "Lenovo"); if (question === "Lenovo") { fu ...

reactjs with axios error message: "Error: Cannot read property 'map' of undefined"

I was experimenting with React and encountered an error while trying to parse JSON data from a localhost server instead of a local file. Despite searching for solutions in other posts, I haven't found a fix yet. I have installed the React Dev Tools ex ...

Styling a single column with two rows and sibling elements using flexbox, similar to the design of the flag of Benin!

To make it easier to understand, I will use the flag of Benin as an example: I have been attempting to achieve a similar layout using flexbox in CSS without success. The challenge is to have each of the three regions as siblings, like this: <div clas ...

Convert Time: segment time devoted to the main content from the time dedicated to advertisements

Can anyone assist me with solving a math problem? Let's consider two lists or arrays: Content Array 0-50 = C1 50-100 = C2 AD Array 10-20 = A1 30-60 = A2 80-140 = A3 The desired output should be: 0-10 = C1 10-20 = A1 20-30 = C1 30-60 = A2 60-80 = C ...

Unable to Upload Image to MySQL Database

I encountered an unidentified index error when trying to upload images. I added a check to prevent the error, but the images are still not being uploaded. I have tested with legitimate images, but nothing seems to work. I've been struggling with this ...

Showing a database table in an HTML format using JavaScript

I am currently working on displaying a database table in HTML. I have written a PHP code snippet which retrieves the table data and formats it into an HTML table without any errors: function viewPlane() { if(!$this->DBLogin()) { $ ...

Showing an image on a blurred background-image at the top of the webpage

Is it possible to overlay an image on top of another image, with the top image appearing blurred in the background? .background-image { background-image: url('https://images.pexels.com/photos/366968/pexels-photo-366968.jpeg?w=1153&h=750&a ...

Having difficulty creating the probot.github app due to an error: The removal of the programmatic API in npm version 8.0.0 causing failure

Currently, I am facing an issue while attempting to set up the probot.github app using the command npx create-probot-app my-first-app which can be found at: . My system is running on the latest node version v19.3.0 with npm version 9.2.0. However, upon exe ...

Leveraging Trustpilot TrustBoxes within a Next.js environment

I'm currently implementing a Trustpilot TrustBox into a Next.js application. Inside my componentDidMount, I have the following code: var trustbox = document.getElementById('trustbox'); window.Trustpilot.loadFromElement(trustbox); In the ...

Validation of form fields appears to be disregarded

I seem to have overlooked a simple issue with this form field validation method. It has worked effectively for me in the past, but now, despite checking all file paths, every time I submit the form, it sends an email regardless of the field content. You c ...

Discovering all links in Selenium by implementing Javascript

I currently have this Selenium Java code snippet. Does anyone know how I can convert it to JavaScript? const webdriver = require('selenium-webdriver'); const By = webdriver.By; const firefox = require('selenium-webdriver/firefox'); (a ...

Even though my form allows submission of invalid data, my validation process remains effective and accurate

Here is the code I have written: <!doctype html> <html lang="en"> <head> <title>Testing form input</title> <style type="text/css></style> <script type="text/javascript" src="validation.js"></script> &l ...

What is the best way to invoke a function from one controller in angularjs to another controller?

I am trying to implement a solution where I need to call the Listing function of testController from userController. I have placed a marker (//) in the code snippet below to indicate where I want to make this function call. This implementation is being d ...

The Proper Way to Include External CSS in a Next.js Page Without Triggering Any Warnings

I find myself in a scenario where I must dynamically inject CSS into a webpage. The content of this page is constantly changing, and I am provided with raw HTML and a link to a CSS file from a server that needs to be displayed on the page. My attempt to ...