Updating the functionality of Bootstrap 4 accordions

Utilizing HTML templates based on Bootstrap 4.3.1, I am delivering educational content to my students. In the current setup, all accordion panels are closed when the page loads, and each panel can be opened independently of others.

To see a live example, visit this CodePen link: https://codepen.io/hagelslag1001/pen/MWGeZJr

Here is the HTML code snippet:

<h2>Accordion: Group of 2</h2>
<p class="small">Accordion: start copy</p>
<!-- Accordion headings should be changed to respect page hierarchy -->
<div class="accordion shadow mb-5">
   <div class="card">
      <div class="card-header">
         <h2 class="card-title">
            Accordion 1 of 2
         </h2>
      </div>
      <div class="collapse">
         <div class="card-body">
            <p>Insert Accordion 1 of 2 content here.</p>
         </div>
      </div>
   </div>
   <div class="card">
      <div class="card-header">
         <h2 class="card-title">
            Accordion 2 of 2
         </h2>
      </div>
      <div class="collapse">
         <div class="card-body">
            <p>Insert Accordion 2 of 2 content here.</p>
         </div>
      </div>
   </div>
</div>
<p class="small">Accordion: end copy</p>

Is there a way to modify this default setting so that only one panel can be open at a time? (Meaning, whenever a new panel opens, the previously open panel closes automatically)

The Bootstrap examples utilize (

data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne"
) to achieve this behavior for accordions in the provided templates

I'm struggling to implement this feature because the structure of the accordion HTML in these templates differs from the Bootstrap 4 examples, which typically use an 'a' or 'button' tag to trigger collapsible events.

Answer №1

Here is a more streamlined solution tailored to your specific CodePen example: https://codepen.io/mrtcntn/pen/MWGeZdP

As stated in the Bootstrap 4 documentation found at this link, it is recommended to use only id="accordion" for the top level div. Avoid unnecessary ids such as id="accordion_1" and id="accordion_2".

I have made adjustments by removing redundant code from the JS and ensuring that id="accordion" is properly added at line 18 in the HTML file.

Answer №2

To achieve this functionality, you can utilize JavaScript to monitor active classes and only permit one at a time. Below is a simplified example of how this can be implemented.

// Access the DOM elements
let nav = document.querySelector(".nav");

// Event handler function 
const clickHandler = function (e) {
  if (e.target.classList.contains("nav__link")) {
    const link = e.target;
    const siblings = link.closest(".nav").querySelectorAll(".nav__link");

    link.classList.toggle("active");

    // Remove all other active classes except for the clicked one
    siblings.forEach((el) => {
      if (el !== link) el.classList.remove("active");
    });
  }
};

// Add event listener
nav.addEventListener("click", clickHandler);
body {
  font-family: sans-serif;
}

.nav__link {
  display: block;
  width: 100%;
}
.active {
  background: #0f0;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div class="nav">
      <ul class="nav__links">
                <li class="nav__item">
                    <a class="nav__link" href="#accordeon--1">Accordion 1</a>
                </li>
                <li class="nav__item">
                    <a class="nav__link" href="#accordion--2">Accordion 2</a>
                </li>
                <li class="nav__item">
                    <a class="nav__link" href="#accordion--3">Accordion 3</a>
                </li>
                <li class="nav__item">
                    <a class="nav__link" href="#accordion--4"
                        >Accordion 4</a
                    >
                </li>
            </ul>
      </div>
    </div>

    <script src="src/index.js"></script>
  </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

Registering a change event for a table's value

I am a beginner in Angular and struggling with writing an event that can successfully pass the changed value from a table cell to my component. Below is the HTML code for the table cell, where the user should be able to change the value and have it passed ...

Styling Navigation in Internet Explorer 7 and 8

I'm encountering issues with a drop-down menu system specifically in IE7 and 8. The functionality is smooth in Chrome and FF, but for some reason, it fails to apply certain styles and ends up misaligned in the IE7 and 8 browsers. You can check it ou ...

Error in Mongoose validation: "Please provide a value for the 'first' field and the 'last' field."

Another user has previously posted a similar question, but I'm still struggling with my MongoDB website. I am working on a project to store names using mongoose. Here is the code for my routes and models: const router = require("express").Router(); c ...

jQuery: Struggling with removing dynamically generated elements

Hey, I've hit a roadblock with this issue and can't figure out why it's not working. To give you an idea of what I'm trying to do, I've put together a jsfiddle: http://jsfiddle.net/ZNbm8/ This is my jQuery code: var count = 0; $ ...

Cross domain tracking pixel implemented using ASP.NET, jQuery, and AJAX technology

Currently, I have a page tracking system that uses $.post(PAIRS-DATA) in JavaScript to send collected information back to the server and load as a tracking pixel. finally { //tracking pixel Response.ContentType = "i ...

Explore the input from multiple users to uncover the word that appears most frequently among them

Hey there (brand new to JavaScript), I am working on a simple program that requires input from multiple users through prompt pop-ups. For example: <script type="text/javascript> var userInput = prompt("Enter your input:"); </script> It&ap ...

Browser resize affects the overlap of DIVs

I've seen similar posts before, but I believe the issue with my website (***) is unique. At full size, the website looks exactly how I want it to. However, when I resize the browser window, the text ("ABOUT INTERNATIONAL PARK OF COMMERCE.." and below ...

What is the method for sending a multipart request using request.js?

I'm stuck on how to send multiple fields via multipart. I know there's a solution using https://github.com/felixge/node-form-data I have all the necessary fields ready and just need to send them as multipart to work with the async result... If ...

Adjust the code to enhance the functionality of web components in Sharepoint

I recently came across some code online that I'm trying to modify in order to add an expanding button next to a web part on my Sharepoint site. However, the problem is that by default, all web parts are already expanded and require a click to collapse ...

Issue with hamburger menu or modal not functioning properly in Rails 4 with Bootstrap 4 alpha3 and JS

I am encountering an issue while implementing the hamburger menu feature in rails 4 with bootstrap 4. Although the menu is displayed, the dropdown section is not functioning correctly. Despite referring to other resources, I have been unable to resolve thi ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

Exploring network connectivity using Node.js

As someone who is just starting out with the node super framework, I'm curious to find out if there's a library or sub framework in Node.js that allows users to ping a server from the frontend of a web app. Ideally, this tool would provide variou ...

Updating HTML content dynamically using Node.js without requiring a page refresh

Currently, I am in the process of learning nodejs and I am looking to dynamically change the content within my HTML without having to completely re-render the entire page every time I make a post. Below is the snippet of code I am currently working with: ...

Is the CSS :not selector failing to operate as expected?

I have been trying to use the :not selector in my code, but for some reason it's not working. I can't figure out why this is happening, especially since the ul element does have the webmedia-gallery class. Any thoughts on what could be causing th ...

Creating designs using HTML5 and implementing them with JAVA for Android development

Hello friends, I am a beginner in android app development and I recently came across some interesting ideas while learning about webviews in android. I am interested in designing an android app using HTML5, CSS3, and JavaScript, while having the coding fu ...

Transforming localhost into a server name in a Node.js environment

Recently I began working on full stack development. I have a physical server and I want to upload my code to it so I can run the NodeJS server from there. This way, when people try to access my site, they will use or instead of localhost:port, which on ...

What is the best way to link my React application with my Express API?

I've been immersed in my react app project for a while now, and I've recently delved into developing a server (using node and express) as well as planning to incorporate a database for it (MongoDB). My client-side react app has been smoothly run ...

How can the input value be transmitted along with the formArray values?

I am currently working with a FormArray in my project where I can add new fields and submit the entire form data on button click. However, I am facing an issue trying to display and send an input field that is connected to the 'name' attribute wi ...

Incorporating fresh components and newly defined attributes in Angular

Is there a way for me to click on a new component button, specify a name, description, select type, and add attributes such as default value and type? I need all this information to be saved and for the new button to appear in the drag-and-drop section. ...

Achieving a seamless scrolling effect using CSS

I recently completed the design of a basic website that includes both mobile and desktop versions. However, I am looking to incorporate some animation into the site to enhance its appearance. One specific feature is a "go up" link at the bottom of the mob ...