How to open offcanvas from offcanvas

Viewed 3155

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
3 Answers

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

Thanks You #Zim. This resolve my issue. I have one question jet. What You think about identify if event was triggered from button on the offcanvas and no triggered from other place? Because now if You click in othe place second canvas is open too

try this


function toggle() {
    document.getElementById('offcanvas').classList.toggle('show');
}

Related