twitter-bootstrapbootstrap-5off-canvas-menu

Bootstrap 5 offcanvas disable close on click


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?


Solution

  • 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