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

8.3k views Asked by At

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

1

There are 1 answers

2
Viliamm On BEST ANSWER

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');