Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to prevent Bootstrap collapse from show based on condition? bs5

I need to prevent collapsible panel to show or open if a specific value is null. it seems easy but I had many attempts and nothing worked.

HTML

<a href="#" data-bs-toggle="collapse" data-bs-target="#infoBox" aria-expanded="false" aria-controls="infoBox"></i>
  
<div class="collapse m-3" id="infoBox">some ifos ...</div>

Fisrt attempt:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var someVal;
var infoBox = document.getElementById('infoBox')
infoBox.addEventListener('show.bs.collapse', function () {
    // console.log(e.target);
    if (someVal == null) return;
})

Second attempt:

var someVal;
var infoBox = document.getElementById('infoBox');
var bsCollapse = new bootstrap.Collapse(infoBox, {
    show: false,
    dispose: true
})
infoBox.addEventListener('show.bs.collapse', function (e) {
    // console.log(e.target);
    if (someVal == null) return bsCollapse;
})

None of them is working

>Solution :

You must use e.preventDefault() function to prevent default.

var toggle = false;

$("#wrapper").on('show.bs.collapse', function (e) {
    if (!toggle) {
      e.preventDefault();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">


<div id="wrapper">
  <a href="#" data-bs-toggle="collapse" data-bs-target="#infoBox" aria-expanded="false" aria-controls="infoBox" id="myCollapsible">press me</a>

  <div class="collapse m-3" id="infoBox">some ifos ...</div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading