Determine if offcanvas element is visible upon initialization in Bootstrap 5 Offcanvas

I have a search-filter offcanvas div for location and property type on this webpage:

On larger screens (desktop), the offcanvas is always visible, but on smaller screens (mobile), it is hidden and can be toggled with a button. This functionality works perfectly.

Now, when the page loads, I want to display the offcanvas if it is currently hidden (on smaller screens) after checking some custom business logic (not discussed in this post).

How can I achieve this?

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 have attempted:

  • I tried searching for *.bs.offcanvas events, but they only trigger after interactions, not during the initial page load when the offcanvas is hidden.
  • Examined the _isShown property of bsOffcanvas, but it returns "false" on desktops, so that doesn't seem to be a viable solution.
  • Explored other properties of bsOffcanvas without success.
  • I may resort to checking the visibility of an element with d-lg-none as a workaround, although it feels somewhat unconventional. However, it will serve as my last option if no better approach is found.

Answer №1

Verifying whether an element is off canvas appears to be similar to Confirming element's off canvas presence.

You can accomplish this by utilizing the following code:

const isOffCanvas = myElement.offsetParent === null;

Answer №2

You have the ability to track changes in media using Window.matchMedia():

var lgBreakpoint, content;

document.addEventListener('DOMContentLoaded', init);

function init() {
  content = document.getElementById('content');

  lgBreakpoint = window.matchMedia("(min-width: 992px)");
  handleChange(lgBreakpoint)
  lgBreakpoint.addListener(handleChange)
}

function handleChange(bp) {
  if (bp.matches) {
    content.innerText = "visible";
    content.style.backgroundColor = 'pink';
  } else {
    content.innerText = "collapsed";
    content.style.backgroundColor = 'lightgreen';
  }
}
@media (min-width: 992px) {
  .offcanvas-collapse {
    display: block;
    position: static;
    top: auto !important;
    right: auto !important;
    bottom: auto !important;
    left: auto !important;
    width: 100% !important;
    max-width: 100% !important;
    /*height: auto !important;*/
    transform: none !important;
    background-color: transparent;
  }
}

.offcanvas-start {
  top: 0;
  left: 0;
  width: 21rem !important;
  border-right: 0 solid transparent;
  transform: translateX(-100%);
}

.offcanvas {
  will-change: transform, box-shadow;
  transition: transform .4s cubic-bezier(0.165, 0.84, 0.44, 1), box-shadow .3s ease;
  box-shadow: none;
  visibility: visible !important;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42202d2d36313630233202776c726c70">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

<div class="container-fluid mt-5 pt-5 p-0 vh-100">
  <div class="row g-0 mt-n3">
    <!-- Filters sidebar (Offcanvas on mobile)-->
    <aside class="col-lg-4 col-xl-3 border-top-lg border-end-lg shadow-sm px-3 px-xl-4 px-xxl-5 pt-lg-2">
      <div class="offcanvas offcanvas-start offcanvas-collapse bg-info vh-100" id="filters-sidebar">
        Filters
      </div>
    </aside>
    <!-- Page content-->
    <div id=content class="col-lg-8 col-xl-9 position-relative overflow-hidden pb-5 pt-4 px-3 px-xl-4 px-xxl-5 vh-100">
      Main content
    </div>
  </div>
</div>

Take a look at the full-page mode output and adjust the browser window size.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the best methods for ensuring a website maintains consistent visibility across all different screen sizes?

Recently, I created a website tailored for a viewport size of 1366px by 768px. My goal is to maintain the same design regardless of the browser window size without implementing responsive design techniques. For instance: When viewing the website on a 360 ...

Tips for transforming the input date value from Mui Datepicker

import * as React from "react"; import moment from "moment"; import TextField from "@mui/material/TextField"; import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs"; import { LocalizationProvider } from &quo ...

Encountering a PropertyTypeError while attempting to process a payment via Stripe in conjunction with use-shopping-cart on Next.js

Upon reaching the checkout page, I encounter the message: Invalid value with type "undefined" was received for stripe. Valid type for stripe is "string". This issue seems to be related to the redirectToCheckout function. Can someone assist me? The cart-s ...

Efficient method for deleting a specific item from a JSON object in React.js

Within the REACT JS framework, I am managing a JSON object in the state component "myrecords". The items within this object are organized by their respective Company Names and have the following structure: { "Master Automotives": [ { ...

Is tabIndex being used as a css property?

I'm trying to understand how to utilize the HTML attribute tabindex using CSS. Specifically, I want to assign tabIndex=0 to all div elements that have the className='my-checkbox'. This is my current approach: <div tabIndex="0" classNam ...

Retrieve a text and save it into a variable

Is there a way to extract a specific string and save it as a variable? For example, if I have the following URL: http://sub.site.com/WordsHere-t.jpg I am looking to extract just WordsHere. The length of this string can vary and will not always be 9 chara ...

Express (generator) is failing to load custom scripts located in the public folder

I'm new to node and express and I'm facing a problem. I want to load a custom script.js from the public folder, but it's not loading. There are no errors in the console or anything in the network tab. When I try to access the URL localhost:3 ...

Identify the failing test cases externally using JavaScript

I am currently tackling an issue where I am seeking to identify the specific test cases that fail when running a test suite for any javascript/node.js application. Finding a programmatic solution is crucial for this task. Mocha testsuite output result Fo ...

When the result of Ajax is identical to that obtained without Ajax, the innerHTML remains the same

I understand that utilizing innerhtml is generally considered a poor practice due to the potential for XSS vulnerabilities (). However, consider the scenario below: I have a webpage generated through a Twig template called index.html.twig. When using te ...

Tips on creating a unique d3js tree design

I am a beginner when it comes to d3js and javascript in general. My goal is to create an interactive IP administration overview using d3js by modeling json data. I know that the key tool for this job is likely d3.layout.tree, which will provide me with the ...

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

What benefits do Adobe Creative Cloud apps offer for developing interactive content in AEM?

My client recently transitioned to AEM for their website, and we are tasked with creating an interactive HTML5 'component' to be embedded on a page. While we have previously used custom HTML5 for components, integrating them into pages on the old ...

Displaying various values from a cascading dropdown in Django

Currently working with Python 3.8 & Django 3.0, I am in need of passing multiple values (volume & volume size) to a dependent dropdown. While I have managed to fill the dependent dropdown with a single value (volume), I have come across some resour ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

What is the best way to update the state by either adding to it or replacing it if the key

I'm currently working on a project involving radio buttons and I need to create dynamic state by setting the initial state on the first click, then updating it with subsequent clicks by either concatenating the new value onto the existing state or rep ...

Rearrange the order of divs dynamically to prevent wrapping/overflow, no need for media queries

Can someone help me with this issue? I am trying to create a navigation bar with centered menus/links, a logo on the left, and call-to-action buttons and icons on the right. If the content overflows or wraps, I want the center column to move to the next l ...

Unable to expand Bootstrap navbar due to collapsing issue

I recently implemented a collapsed navbar on my website using bootstrap. However, I'm facing an issue where it does not open when clicking on the hamburger menu. After researching various solutions for this problem and trying them out, none of them s ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Node.js application - varying NODE_ENV upon NPM launch

Operating my node.js application can be quite confusing. When launched by npm start, it operates in "production" mode, whereas when launched using node start.js, it runs in 'development' mode. I want to ensure that the 'development' mo ...