Search code examples
bootstrap-5off-canvas-menu

Bootstrap 5 : offcanvas, how to close it on mouse leave?


i want to create a website with a navbar using offcanvas. It's works great but i want to implement a close navbar on mouse leave function.

Do you have any suggestion to do this?

Thank you guys


Solution

  • In BS5 it is pretty easy, especially if you use vanilla JS:

    function offCanvasListener(offCanvasId) {
      let myOffCanvas = document.getElementById(offCanvasId);
    
      const hideCanvas = () => {
        let openedCanvas = bootstrap.Offcanvas.getInstance(myOffCanvas);
        openedCanvas.hide();
        event.target.removeEventListener('mouseleave', hideCanvas);
      }
      const listenToMouseLeave = (event) => {
        event.target.addEventListener('mouseleave', hideCanvas);
      }
      
      myOffCanvas.addEventListener('shown.bs.offcanvas', listenToMouseLeave);
    }
    
    
    //function call
    offCanvasListener('offcanvasExample');