Tips for locating numerous div IDs within JavaScript snippets

In my Bootstrap 4 project, I came across a helpful solution on Stack Overflow for creating a dropdown accordion style using JavaScript (Twitter Bootstrap: How to create a dropdown button with an accordion inside it?). I customized the script for my website's navigation but encountered an issue where the JavaScript only targets the ID "accordion" and not other IDs like "accordion1." This poses a problem when navigating out of the menu as only the first panel is affected. Unfortunately, I can't use the form tag method outlined in Bootstrap 4: How to create a dropdown menu with an accordion inside it?. You can view a sample on Codeply

My question also relates to opening multiple accordion panels simultaneously.

<div class="collapse navbar-collapse " id="navbarContent">
                <ul class="navbar-nav">
                    <li class="nav-item dropdown dropdown-accordion " data-accordion="#accordion">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                        ONBOARDING
                        </a>

                        <div class="dropdown-menu ">
                            <div class="accordion" id="accordion">
                                <div>
                                    <a class="nav-link" href="#" target="_blank">
                        Item 01
                            </a>
                                </div>
                                <div>
                                    <a class="nav-link" data-toggle="collapse" role="button" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                        Item 02
                        </a>
                                    <div id="collapseOne" class="collapse" aria-labelledby="headingOne">
                                        <div> <a class="nav-link" href="#" target="_blank">
                                        Item 02A</a>
                                        </div>
                                        <div> <a class="nav-link" href="#" target="_blank">
                            Item 02B
                                </a></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>

                    <li class="nav-item dropdown dropdown-accordion " data-accordion="#accordion">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            OFFBOARDING
                        </a>

                        <div class="dropdown-menu ">
                            <div class="accordion" id="accordion1">
                                <div>
                                    <a class="nav-link" href="#" target="_blank">
                        Item 01
                            </a>
                                </div>
                                <div>
                                    <a class="nav-link" data-toggle="collapse" role="button" data-parent="#accordion1" href="#collapsetwo" aria-expanded="true" aria-controls="collapsetwo">
                        Item 02
                        </a>
                                    <div id="collapsetwo" class="collapse px-3" aria-labelledby="headingOne">
                                        <div> <a class="nav-link" href="#" target="_blank">
                            Item 02A
                                </a></div>
                                        <div> <a class="nav-link" href="#" target="_blank">
                            Item 02B
                                </a></div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>
            </div>

    <script>
        $('.dropdown-accordion').on('show.bs.dropdown', function(event) {
            var accordion = $(this).find($(this).data('accordion'));
            accordion.find('.show').collapse('hide');
        });
$('.dropdown-accordion').on('click', 'a[data-toggle="collapse"]', function(event) {
        event.preventDefault();
        event.stopPropagation();
        $($(this).data('parent')).find('.collapse.show').collapse('hide');
        $($(this).attr('href')).collapse('show');
    })
    </script>

Answer №1

Based on the information in your code snippet, it appears that you are simply concealing the div with the id 'accordion'. To conceal all of them, you need to determine the number of accordions present and iterate through each one.

    <script>
        $('.dropdown-accordion').on('show.bs.dropdown', function(event) {
            for(var i = 0; i < numberOfAccordions; i++)
            {
               var accordion = $(this).find($(this).data('accordion'+i));
               accordion.find('.show').collapse('hide');
            }
        });
    </script>

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

The current status of Dropzone.js is in a pending state, preventing the upload of any

I have integrated Multer in the back-end for file upload handling and Dropzone.js in the front-end. Testing my back-end code with Postman works perfectly, but when using Dropzone, the status remains pending and the file does not get uploaded. After waiting ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

The Material UI appbar fails to resize properly on mobile devices

I have added a material-ui appbar to the top of my website. Check it out here: Website Appbar However, when I resize the website to mobile size, the appbar does not adjust responsively to the screen. Here's how it looks on mobile: Appbar when in mobi ...

iOS 10's autofocus feature experiencing difficulties in focusing on input

While using an application on my desktop or Android device, I have noticed that the input focus works perfectly fine. However, when I try to run the same application on iOS 10 Safari, the input focus does not seem to be working. It is worth noting that I ...

Unable to modify the name of an element's class due to restrictions in JavaScript

I am trying to switch the class of an element from score -box1 to score -box1.-active. I defined a constant $target in order to access the class score -box1, however it is not functioning as expected. const $target = document.getElementByClassname('sc ...

Error in Node.js: the function "myFunction" is not defined

Utilizing the fcm-node package to facilitate sending notifications from the Express API route to the app via a registration token. The function being used is as follows: const FCM = require('fcm-node'); const serverKey = ... const fcm = new FCM( ...

Using JavaScript/JQuery, change relative or viewport sizes to fixed sizes when the page loads

Wishing you a delightful day. As I work on my website, I find myself relying heavily on viewport units like vw and vh for all measurements such as font size, padding, margin, width, and height. These units provide the flexibility needed to ensure that the ...

The Angular directive ng-model is not able to return a value

I'm currently troubleshooting an issue with the filters in an older project. Here's the HTML snippet: <input type="text" class="form-control" ng-model="FilterEventsEdit" ng-change="FilterEvents()" ...

passing a javascript variable to html

I am facing an issue with two files, filter.html and filter.js. The file filter.html contains a div with the id "test", while the file filter.js has a variable named "finishedHTML." My objective is to inject the content of "finishedHTML" into the test div ...

Do not attempt to log after tests have finished. Could it be that you overlooked waiting for an asynchronous task in your test?

Currently, I am utilizing jest in conjunction with the Vue framework to create unit tests. My test example is successfully passing, however, I am encountering an issue with logging the request. How can I resolve this error? Is there a mistake in my usage o ...

The resolution of the Ajax call promise remains elusive

When I make an AJAX call to a REST API in my JavaScript code, the purpose is to fetch a JSON file. The structure of the AJAX call resembles something like this: $.ajax(ajaxObj).then(function(response) {}).catch(function(err) {}); The network monitor refl ...

The image is not displaying on the page

Slider Section (Gray Part) We verified after loading, and the data was spot on. In development mode (F12), we can inspect object information (ImgURL, Text, etc.). However, it is not being displayed. Below is the template code and script code. Thank you. ...

Exploring the World of Github on Windows: Understanding the 'master' and 'gh-pages' Branches

I have developed a simple jQuery plugin and uploaded it to Github. I am using both the Github website and Github for Windows to manage this project. However, when I try to include the .js or .css files from Github using the Raw links, my browser fails due ...

Creating a triangle shape using Bootstrap to style a div element, similar to the image provided

Trying to achieve the look of the attached image with a few divs. I know I can use a background image like this: background:url(image.png) no-repeat left top; But I'm curious if there's another way to achieve this without using a background ima ...

Flexbox alignment issue: Text is not vertically centered

I'm facing an issue with centering my content vertically. Upon inspecting the divs, I noticed some empty space below them that seems to be causing the problem. When I tried adding <line-height: 3> in the dev tool styles, it seemed to center prop ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Upon calling the createModalAddPost() function, a single window is triggered to open

Hey there, I'm having a JavaScript question. So, I have a panel that opens a window, and it works fine. But the issue arises when I close the window and try to open it again - it doesn't work. I have to reload the page every time in order to open ...

The latest URL is not launching in a separate tab

Looking for some assistance with this code snippet: <b-btn variant="primary" class="btn-sm" :disabled="updatePending || !row.enabled" @click="changeState(row, row.dt ? 'activate' : 'start&apo ...

Materialize CSS is throwing an error: 'velocity is not a function'

Encountering an issue with Materialize CSS. A JavaScript error appears 'I('.velocity is not a function', for certain actions. For instance, clicking the collapse icon on the sidenav results in e.velocity is not a function error. Similarly, u ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...