Search code examples
javascripthtmljquerybootstrap-5

How to open offcanvas from offcanvas


I have a little problem with open one offcanvas from previous canvas. Generally I have canvas like this using bootstrap 5:

<button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasBottom" aria-controls="offcanvasBottom">Toggle bottom offcanvas</button>

<div class="offcanvas offcanvas-bottom" tabindex="-1" id="offcanvasBottom" aria-labelledby="offcanvasBottomLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="offcanvasBottomLabel">Offcanvas bottom</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body small">
    <button class="btn btn-primary" type="button" data-bs-toggle="offcanvas" data-bs-target="#secondoffcanvas" aria-controls="offcanvasBottom" data-bs-dismiss="offcanvas">Open second offcanvas</button>
  </div>
</div>

second offcanvas:

<div class="offcanvas offcanvas-bottom" tabindex="-1" id="secondoffcanvas" aria-labelledby="offcanvasBottomLabel">
  <div class="offcanvas-header">
    <h5 class="offcanvas-title" id="offcanvasBottomLabel">Offcanvas bottom</h5>
    <button type="button" class="btn-close text-reset" data-bs-dismiss="offcanvas" aria-label="Close"></button>
  </div>
  <div class="offcanvas-body small">
    second content
  </div>
</div>

My scenario:

  1. Click to open first offcanvas
  2. Click on the button in canvas Resulst:
  • first canvas hide
  • second canvas open

Solution

  • Read "how it works"...

    "Similar to modals, only one offcanvas can be shown at a time."

    However, you can open one from the other. Programmatically show the 2nd when the 1st is hidden...

    var offcanvasBottom = document.getElementById('offcanvasBottom')
    var secondoffcanvas = document.getElementById('secondoffcanvas')
    
    offcanvasBottom.addEventListener('hidden.bs.offcanvas', function () {
      var bsOffcanvas2 = new bootstrap.Offcanvas(secondoffcanvas)
      bsOffcanvas2.show()
    })
    

    Demo