Accordion - Conceal Previously Revealed Items

I'm currently working on finding a solution to hide all child sections that are open in my accordion when a new header is clicked. I've included a jsfiddle link to show what I have so far. Any suggestions on how to close the opened sections would be greatly appreciated. Thank you!

html

<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<div class="w3-container">

<h2>Active Accordions</h2>
<p>In this example we add the w3-red class to an active accordion (when the button is clicked on and the content is opened).</p>

<button onclick="myFunction('Demo1')" class="w3-button w3-block w3-black w3-left-align">Open Section 1</button>
<div id="Demo1" class="w3-hide w3-container">
    <p>Some text..</p>
</div>

<button onclick="myFunction('Demo2')" class="w3-button w3-block w3-black w3-left-align">Open Section 2</button>
<div id="Demo2" class="w3-hide w3-container">
    <p>Some other text..</p>
</div>

</div>

</body>
</html>

js

function myFunction(id) {
    var x = document.getElementById(id);
    if (x.className.indexOf("w3-show") == -1) {
        x.className += " w3-show";
        x.previousElementSibling.className = 
        x.previousElementSibling.className.replace("w3-black", "w3-red");
    } else { 
        x.className = x.className.replace(" w3-show", "");
        x.previousElementSibling.className = 
        x.previousElementSibling.className.replace("w3-red", "w3-black");
    }
}

https://jsfiddle.net/2eda9kz5/1/

Answer №1

Utilizing toggle is essential as it has the ability to reveal or conceal the corresponding element. Make sure to refer to the jQuery documentation for more information: http://api.jquery.com/toggle/

Be sure to also take a look at this insightful answer! It provides instructions on how to close all other elements except for the one you have selected. JQuery: Toggle Element that is clicked and hide all other

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

Enhance your React Routing using a Switch Statement

I am currently developing a React application where two distinct user groups can sign in using Firebase authentication. It is required that each user group has access to different routes. Although the groups share some URLs, they should display different ...

Managing image alignment in flexbox containers with nested rows and columns

In the following design demonstration, there are three blocks to explore. Block 1: Consists of three columns. The middle column contains two rows, both set to flex:1. Block 2: Also has three columns. The middle column includes two rows, but with a unique ...

Encountering a ReferenceError in Angular 4 due to d3 not being defined when importing in a module

I'm looking to incorporate these imports into my angular 4 app.module, rather than adding them directly to my index file. In app.module.ts -> import d3 from "d3"; console.log(d3) // Confirming successful import of D3 import nvd3 from "nvd3"; H ...

What is the best way to utilize JavaScript for both server-side and client-side development, all while effectively sharing code between the two

Recently, I've been brainstorming a side project that I want to dive into for fun. As I explore options, I find myself searching for examples, libraries, and frameworks that could streamline the process of sharing code between the client and server. ...

Is it possible to ensure that a newly created element functions in the same way as an existing element?

I am currently in the process of developing an application that empowers users to generate new items, modify existing items, or delete items by utilizing corresponding icons located adjacent to each item. When it comes to existing items, the action icon d ...

Problems with implementing media queries in CSS

Our team is currently delving into the realm of responsive design and experimenting with a mobile-first framework. In an attempt to utilize media queries to adjust our layout based on screen size, we have crafted the following CSS: .flex, .cards, .card { ...

Find the two numbers within a specific range in an array using jQuery

I have two arrays and I need to check for any duplicate ranges. How can I achieve this? let startingArray = ['1', '6.1', '10', '31','6.2',3]; let endingArray = ['2', '9.9', '30&ap ...

What is the process for showing a duplicate image in a dialog box once it has been selected on an HTML page?

I am experiencing an issue where the dialog box is displaying when I use the button tag, but not when I use the image tag. Can someone please assist? <img src='image.png' height='200px' widht='200px' id='1'> ...

Tips for stopping the entire webpage from scrolling in Vuetify

Hey there, I'm facing an issue with scrolling on mobile devices and iPads. When I view my site on desktop, there is no scrolling behavior, but as soon as I switch to a mobile device or iPad, the scroll appears. This problem is specific to mobile devic ...

The viewport scaling issue occurs when transitioning from landscape to portrait orientation

While developing a mobile version of my website, I have encountered an issue with the behavior when rotating my iPhone device. Everything looks fine in landscape orientation, but upon rotation back to portrait, the viewport remains stuck at the landscape s ...

Enhancing your website's design with dynamic CSS variables using JavaScript

Is there a way to update CSS variables specifically scoped under a certain CSS class (or even other complex CSS selectors) that are predefined in a stylesheet? This question extends beyond just CSS variables and includes other CSS properties as well, quest ...

Tailored design - Personalize interlocking elements

I am currently working on a custom theme and I am trying to adjust the font size of Menu items. In order to achieve this, I have identified the following elements in the tree: ul (MuiMenu-list) MuiListItem-root MuiListItemText-root If I want to modify th ...

Setting constraints for table size with min-width and max-height

I have a coding dilemma involving the min-width and max-height properties in my table. The issue arises when I try to set these properties on the td element – they are being ignored by the browser. If I nest a div with the properties inside a td, the con ...

Dealing with errors in Express.js within the service or controller layers

Currently, I am developing an Express.js application with a distinct controller layer and service layer. Below you can find the code snippet I have implemented so far: user.service.js exports.registerUser = async function (email, password) { const hash ...

My objective is to upload a video file and store it on the server using multer

My goal is to effectively receive and save a video file in the uploads folder with the proper extensions using node, express, and multer. Despite successfully passing the video to the server, it doesn't save as intended. Below is my backend code snipp ...

What is the correct way to call upon Bootstrap's CSS that was obtained through a Gradle dependency?

I'm having trouble referencing the Bootstrap library from the 'External Libraries' section in my project. In my build.gradle file, I included: compile group: 'org.webjars', name: 'bootstrap', version: '3.3.7' ...

Convert a solo row into individual columns within a grid format

My goal is to design a grid layout where each row can be divided into columns independently, similar to the example shown below: https://i.stack.imgur.com/VFPFq.png Here's the code snippet I have been experimenting with: .container { position ...

Encountering a VueJS error when trying to locate a module while using a JSON file

I've been tasked with finding a solution to dynamically import pages within vuejs projects that are being built with a CLI tool by my team. I initially attempted to use functions as a string ("() => import(...)") and then evaluate that string, but ...

The content at “http://localhost:3000/script.js” could not be accessed because of a MIME type mismatch with the X-Content-Type-Options set to nosniff

I encountered an issue while attempting to transfer all the JavaScript to a separate js file and then adding that js file to the html per usual. The console displayed the following error message: The resource from “http://localhost:3000/public/main.js” ...

Lost in a sea of confusion with ember-cli-postcss and autoprefixer

I'm currently working on an ember build that incorporates autoprefixer. My issue arises from the fact that the output location for 'assets/application-name.css' has shifted from its normal path to 'app/styles/app.css', and I would ...