skip to Main Content

I have a navbar with several buttons that make divs appear underneath.

<a data-bs-toggle="offcanvas" href="#select" role="button" aria-controls="select"></a>
<div id="select" class="offcanvas offcanvas-start" tabindex="-1" data-bs-backdrop="false">
    Foobar
</div>

I also need to open these windows programmatically. For example, if I initially use $('#select').collapse('show') nothing happens.

However, if I first click on the A tag and then execute the line of code $('#select').collapse('toggle') I am able to hide/show the window. However, if I try to click on the A tag again, it tells me

Bootstrap doesn’t allow more than one instance per element. Bound instance: bs.collapse

Roughly speaking, I should add the class "show" to the div with id="select" and then set "visibility: visible"; to the div. However then clicking again on the A tag skips a loop, and I have to click twice to make the div disappear again.

3

Answers


  1. In JQuery you can show elements using $("#something").show(); and hide with $("#something").hide();

    Login or Signup to reply.
  2. You could do something like this-

    Keep track of a flag where it changes to true or false each time you click. Use the CSS properties in the function whether to display or not.

    HTML-

     <a data-bs-toggle="offcanvas" onclick="changeflag()" href="#select" role="button" aria-controls="select">Select</a>
        <div  id="select" class="offcanvas offcanvas-start" tabindex="-1" data-bs-backdrop="false">
        Foobar </div>
    

    In tag,

    <script>
            var flag=false;
            window.onload = function() {
                document.getElementById("select").style.display = 'none';
            };
       
          function changeflag(){
              if(flag==false){
                  
                  flag=true;
                  console.log(flag);
                  document.getElementById("select").style.display = 'block';
              }
              else if(flag==true){
                  
                  flag=false;
                  console.log(flag);
                  document.getElementById("select").style.display = 'none';
              }
              
          }
      </script>
    
    Login or Signup to reply.
  3. From your code, it seems like you are mixing Bootstrap’s collapse and offcanvas functionalities.
    Since you’re using offcanvas, you should use Bootstrap’s offcanvas API methods rather than the collapse API.
    For example:

    var myOffcanvas = document.getElementById('select'); 
    var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas); 
    bsOffcanvas.show(); 
    // To hide the offcanvas 
    bsOffcanvas.hide();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search