2

I'm using the offcanvas component (https://getbootstrap.com/docs/5.0/components/offcanvas/). However I was wondering if it is possible to prevent it from closing when I click outside the offcanvas window. I've managed to stop it from closing when I press ESC but theres no way (as far as the docs go) to prevent it from closing when I do a mouse click outside of the offcanvas. Does anyone have an idea?

EDIT: I managed to get it working halfway by listening for the hide.bs.offcanvas event and then using e.preventDefault(); However now I'm unable to close the offcanvas with its default close button because it will always cancel the hide event. Any ideas?

Zim
  • 296,800
  • 77
  • 616
  • 554
sharpness
  • 51
  • 1
  • 4

1 Answers1

1

Bootstrap adds a click listener to the body. Therefore, you would attach a click event listener to the body, and stop the event from propagating...

document.body.addEventListener('click', function(e){
    e.stopPropagation()
})

Demo

Zim
  • 296,800
  • 77
  • 616
  • 554
  • Thanks a lot! This seems to work, is this fine to use though? Won't this cause other events/document click listeners to not behave properly? Just wondering – sharpness Apr 07 '21 at 14:10
  • It would only impact listeners attached to the body (which the developer should be aware of!). As you can see from the demo it doesn't cause issues with the other Bootstrap events.. and it's the only way to address the question you asked. – Zim Apr 07 '21 at 14:45