Friday, 17 December 2021

Bootstrap 5 Offcanvas - Detect if offcanvas item is displaing on load

I have a search-filter div offcanvas, like the location, property type etc on this page: https://finder.createx.studio/real-estate-catalog-rent.html

On desktop devices (=>lg) , it displays the "offcanvas" permanently, on mobile (<lg) it is hidden "off canvas" and can be toggled using a button. That all works great.

When the page loads, IF the offcanvas element is actually offcanvas (ie <lg), I want to run some javascript to display it (after another business logic check, out of scope for this post).

How can I do that?

Something like this:

var myOffcanvas = document.getElementById('filters-sidebar');
var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas);
var myCustomBusinessLogicCheck = true;
var isTheOffcanvasActuallyOffCanvasRightNow = ?? //detect if offcanvas element is currently actually off-canvas

if (isTheOffcanvasActuallyOffCanvasRightNow  & myCustomBusinessLogicCheck) {
    bsOffcanvas.show();
}

What I tried:

  • I tried looking for the *.bs.offcanvas events - but they do not fire when the page first loads (and the offcanvas initially "hides"), only on subsequent interactions.
  • Looked at the _isShown property of bsOffcanvas - but it returns "false" on desktop, so it seems I can't use that.
  • Poked around other properties on bsOffcanvas but didn't find anything obvious
  • I could maybe track if an element with d-lg-none is visible or not, but it feels hacky. However, it will be my fallback if I do not find a cleaner way.


from Bootstrap 5 Offcanvas - Detect if offcanvas item is displaing on load

No comments:

Post a Comment