1

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

Lanfeust2100
  • 23
  • 1
  • 5

1 Answers1

3

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

Viliamm
  • 618
  • 5
  • 12
  • thank you so much , that is exactly what i need – Lanfeust2100 Jun 01 '21 at 15:43
  • @Lanfeust2100 I edited my answer. I was accidentaly removing wrong event listener in hideCanvas. Now it is fixed. The functionality is the same. Now it adds and removes mouseleave event from offCanvas. In the previous code it added mouseleave and removed shown.bs.offcanvas events. It worked properly, but it was not correct. Now it is fine. I was glad to help. – Viliamm Jun 02 '21 at 05:32