Bootstrap 5 offcanvas disable close on click

Viewed 3309

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?

5 Answers

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

I found a CSS only solution for this by setting pointer-events:none on the offcanvas-backdrop class. The exact CSS style would be

.offcanvas-backdrop.fade.show {
 pointer-events:none 
}

This will prevent any click events on the offcanvas' backdrop and click events inside the offcanvas will work as usual.

By using beforeDismiss return false, it won't close on dismiss option, since click on backdrop is pointed to dismiss it won't close the offcanvas, in order close the offcanvas we can use close method

ngbCanvasOptions: NgbOffcanvasOptions = {
    beforeDismiss: () => {
      return false;
    },
    keyboard: false,
    animation: true
  };

I don't love this solution, but it works for my needs as of today. (I'm really hoping Bootstrap will give us this functionality ASAP.)

$("#myOffcanvas").on("shown.bs.offcanvas", function () {
    const backdrop = $(".offcanvas-backdrop");
    const parent = backdrop.parent();
    const cloned = backdrop.clone();
    backdrop.remove();
    parent.append(cloned);
}).on("hide.bs.offcanvas", function () {
    $(".offcanvas-backdrop").remove();
});

Setting data-bs-keyboard="false" as a data-attribute of the off-canvas element seems to work in Bootsrap 5.1.1

Related