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:

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>

Leave a Reply