JavaScript Logic to Check if an Element is Hidden

I'm having trouble figuring out how to close an element when another element collapses. I've searched for solutions without success.

My structure is updated using Bootstrap and JavaScript, but it doesn't function as expected. Specifically, when collapsing the first sub-menu (

<div class="collapse list-group-sub-menu spacer" id="subMenu1">
), I also want the second sub-menu to collapse. In my project, all divisions are in rows, otherwise, I would have used a different method.

HTML


<div class="container">
    <div class="row">
        <div class="col-md-6">
            <table class="table table-responsive">
                <tbody>
                    <tr>
                        <td class="col-lg-10">
                            <div id="bar1">
                                <div class="list-group panel">
                                    <a class="list-group-item list-group-item-warning">Menu</a>
                                    <!--"collapse in" to keep it open from the start-->
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse in" id="sidebar1">
                            <a href="#subMenu1" onclick="SubMenu()" class="list-group-item" data-parent="#sidebar1" data-toggle="collapse">Item 1 <i class="fa fa-caret-down"></i></a>
                            <a href="#" class="list-group-item">Item 2</a>
                            <a href="#" class="list-group-item">Item 3</a>
                            <a href="#" class="list-group-item">New <i class="fa fa-plus-circle"></i></a>
                        </div>
                    </td>
                </tr>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse list-group-submenu spacer" id="subMenu1">
                            <a href="#" class="list-group-item" data-parent="#subMenu1">Item 1.1</a>
                            <a href="#" class="list-group-item" data-parent="#subMenu1">Item 1.2</a>
                            <a href="#subSubMenu1" onclick="SubSubMenu()" class="list-group-item" data-toggle="collapse">Item 1.3 <i class="fa fa-caret-down"></i></a>
                            <a href="#" class="list-group-item">Item 1.4</a>
                            <a href="#" class="list-group-item">New <i class="fa fa-plus-circle"></i></a>
                        </div>
                    </td>
                </tr>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse list-group-submenu list-group-submenu-1 spacer" id="subSubMenu1">
                            <a href="#" class="list-group-item">Item 1.3.1</a>
                            <a href="#" class="list-group-item">Item 1.3.2</a>
                            <a href="#" class="list-group-item">New <i class="fa fa-plus-circle"></i></a>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
        <div class="col-md-6">
            <table class="table table-responsive">
                <tbody>
                    <tr>
                        <td class="col-lg-10">
                            <div id="bar2">
                                <div class="list-group panel">
                                    <a class="list-group-item list-group-item-warning">Menu</a>
                                    <!--"collapse in" to keep it open from the start-->
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse in" id="sidebar2">
                            <p class="list-group-item" data-parent="#sidebar2">Item 1</p>
                            <p class="list-group-item">Select
                                <input type="checkbox" /> </p>
                            <p class="list-group-item">Select
                                <input type="checkbox" />
                            </p>
                            <a href="#" class="list-group-item">New <i class="fa fa-plus-circle"></i></a>
                        </div>
                    </td>
                </tr>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse list-group-submenu" id="subMenu2">
                            <p class="list-group-item" data-parent="#subMenu2">Select
                                <input type="checkbox" />
                            </p>
                            <p class="list-group-item" data-parent="#subMenu2">Select
                                <input type="checkbox" />
                            </p>
                            <p class="list-group-item">Item 1.3</p>
                            <p class="list-group-item">Select
                                <input type="checkbox" />
                            </p>
                            <p class="list-group-item">New <i class="fa fa-plus-circle"></i></p>
                        </div>
                    </td>
                </tr>
            </table>
            <table class="table table-responsive">
                <tr>
                    <td>
                        <div class="collapse list-group-submenu list-group-submenu-2" id="subSubMenu2">
                            <p class="list-group-item">Select
                                <input type="checkbox" />
                            </p>
                            <p class="list-group-item">Select
                                <input type="checkbox" /> </p>
                            <p class="list-group-item">New <i class="fa fa-plus-circle"></i></p>
                        </div>
                    </td>
                </tr>
           </table>
        </div>
    </div>
</div>

SCRIPTS


function SubMenu() {

    $('#subMenu1').collapse("toggle");

    $('#subMenu1').is('collapse', function(){
        SubSubMenu();
    });
}


function SubSubMenu() {
    $('#subSubMenu1').collapse("toggle");
    $('#subSubMenu2').collapse("toggle");
}

Answer №1

As per the guidelines provided on Bootstrap's documentation, the collapse feature is controlled using specific CSS classes.

.collapse: This class hides the content.

.collapsing: Applied during transitions.

.collapse.show: Displays the content.

To determine if a collapsible element is currently collapsed, you can use the selector .collapse:not(.show).

if($('#subMenu1').is('.collapse:not(.show)')) {
    // Perform an action
}

Answer №2

To ensure that "child collapsible elements" are hidden when their parent is hidden, you can use the

on('hidden.bs.collapse', function)
method. Here's an example snippet to demonstrate this:

$("#collapse1").on('hidden.bs.collapse', function(){
  $("#collapse1 .collapse").collapse('hide');
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

<div class="panel-group">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h4 class="panel-title">
        <a id="lnk1" data-toggle="collapse" data-target="#collapse1" href="#collapse1">Menu 1</a>
      </h4>
    </div>
    <div id="collapse1" class="panel-collapse collapse">
      <div class="panel panel-default">
          <h3 class="panel-title">
            <a data-toggle="collapse" href="#collapse2">Sub menu 1</a>
          </h3>
      </div>
      <ul class="list-group">
        <li class="list-group-item">
          <div id="collapse2" class="panel-collapse collapse">
            <ul class="list-group">
            <li class="list-group-item">Item 1</li>
            <li class="list-group-item">Item 2</li>
            </ul>
          </div>
        </li>
      </ul>
    </div>
  </div>
</div>

Answer №3

If you are looking for a simple vanilla JavaScript solution (as per your original request), here is a general approach that can be tailored to fit your specific needs.

I have taken the HTML markup from Bootstrap4 and included an ID selector for reference.

<button class="btn btn-lightgreen" type="button" id="collapsebutton" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">Button with data-target</button>
<div class="collapse" id="collapseExample">
<div class="card card-body">Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident.
</div>

<script>
 var clickbutton = document.getElementById('collapsebutton');
 clickbutton.addEventListener('click', collapseclick);
 function collapseclick () {
   var closed =  this.getAttribute('aria-expanded');
   if (closed=='false') {
     alert("now open");
     //perform actions...
   }
 }
</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

Having Trouble Importing a Dependency in TypeScript

My experience with using node js and typescript is limited. I attempted to include the Paytm dependency by executing the following code: npm install paytmchecksum or by inserting the following code in package.json "dependencies": { ... & ...

Inserting a line break in real-time within a JSX statement

Currently working on a React application that retrieves song lyrics from an API. The API provides me with a lyrics_body attribute as a string, which I use to showcase the lyrics on the webpage. However, when React renders it, the format is not ideal becau ...

Using jQuery to send LocalStorage data to an email address with the help of PHP

Currently, I am in the process of developing a basic eCommerce/checkout system. My goal is to utilize localStorage data and transfer it to PHP using jQuery or any other method that is convenient. However, when I attempted to send the email, I only received ...

Neglect to notify about the input text's value

Having trouble retrieving the text from a simple <input id="editfileFormTitleinput" type="text>. Despite my efforts, I am unable to alert the content within the input field. This is the code snippet I've attempted: $('#editfileFormTitleinp ...

What is the purpose of storing JSON data as a string within another JSON object?

Screenshot of developer tools While exploring the local storage on my visit to YouTube, I came across some very peculiar-looking JSON data. { creation: 1638112285935, data: "{\"quality\":1080,\"previousQuality&bs ...

Is it possible to use both MUI makeStyles and Theming in the _app.js file?

I've been working on a complex navigation component using MUI Persistent Drawers within a React + Next.js setup. To achieve the desired content shrinking effect based on state changes, I ended up placing the entire navigation system inside the _app.js ...

Trouble with downloading a file from an HTML hyperlink

When I attempt to download a file from my file folder using the absolute path <a href='N:\myName\test.xlsx'>download</a>, the file opens directly instead of downloading. However, if I use the relative path <a href=&apos ...

HackerRank Challenge: Strategies for Efficiently Solving Minimum Swaps 2

In this challenge, the goal is to determine the minimum number of swaps needed to arrange an array of disordered consecutive digits in ascending order. My code successfully handles most of the tests, but I'm encountering timeout errors with four speci ...

Utilizing Parent Method in VueJS Component: A Step-by-Step Guide

I need to access methods of the parent component from within the current one, without using props. Below is the structure in HTML: <div id="el"> <user v-for="user in users" :item="user"></user> </div> And here is the Vue code ...

Updating $data within a VueJS directiveIs there something else you

We have a component and a directive. The structure of our component data is as follows: { langs: [ { title: '', content: '' }, { title: '', content: ...

Eliminate the table background effect on hover using HTML and CSS

If you need assistance with a contact form, please visit this link. There seems to be an issue with the hover effect on the fields causing them to turn dark grey. This may not align with your desired plain white background. You can view a screenshot https ...

Issue with Bootstrap 5 navbar failing to collapse

Encountered an issue with the Bootstrap 5 navbar toggle feature - it's not toggling as expected. Interestingly, the exact code works perfectly fine with Bootstrap 4. Attempts to rectify the situation by removing the navbar-toggler class from the butt ...

On paste events, CKEditor will strip away all HTML tags except for div and span elements

I am trying to implement a feature in CKeditor where all HTML tags are removed when a user pastes content using Ctrl+v. The code I have written so far does not seem to work as expected. <script type="text/javascript"> CKEDITOR.on('instanceR ...

Troubleshooting AWS S3 SDK upload error when sending data from Next.js API endpoint hosted on Vercel - ERR_HTTP_HEADERS_SENT

I'm currently working on uploading a file from my Next.js API endpoint running on Vercel using the @aws-sdk/client-s3 package. Here's a snippet of my code: import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; import type { N ...

The glitch in jQuery's animate function callback

In my code to animate the sliding out of a div, I encountered an issue: var current = $('.s_text:visible'); current.animate({ right: 1014, opacity:0, },{queue: false, duration:2000}, function() { current.hide(); }); Strangely, the callbac ...

Is Angular's promise implementation asynchronous in nature?

I can't seem to figure out the behavior of Angular's promises. Are promises actually asynchronous? I'm a bit confused about this concept. When using promises in my code to handle a large process (such as reading and writing hundreds of big ...

What could be causing my buttons to malfunction once I've applied padding to the container?

I'm struggling with getting my buttons to appear active. They currently don't have any functionality and lack a hover effect when clicked. Despite my efforts to add effects, nothing seems to change. After experimenting with the CSS, I've no ...

Looking to obtain the coordinates of a draggable element?

After dragging a div around the page and submitting a form, I would like to capture its location on the page so it can render in that same spot when the page reloads. My current question is how can I capture the coordinates or location of the div after it ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

Struggling to retrieve an integer value from user input?

Hey there! I am facing an issue where I receive data from a form via POST, and some fields need to be treated as integers. However, when I use: var_dump($_POST) All the data is returned as strings enclosed in double quotes, which I would like to remove. ...