How can I trigger the offcanvas opening in Bootstrap 5 through code?

I am having an issue with a bottom offcanvas on my webpage. I want to open it when a card is clicked, but despite trying to set the necessary attributes and using code from the documentation, it only shows the backdrop briefly before immediately dismissing.

Here is the code snippet I have attempted:

const products = document.getElementsByClassName("card product");

var productClick = function (event) {
    event.preventDefault()
    var myOffcanvas = document.getElementById('offcanvasBottom')
    var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
    bsOffcanvas.show();
};

Array.from(products).forEach(function (element) {
  element.addEventListener("click", productClick);
});
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74161b1b00070006150434415a445a45471e131d051b091e1602004356">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd9d4d4cfc8cfc9dacbfb8e958b958beeee8593decccc95dadbcfdf81cecc99bddbac910dbfeeedd">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>


<div class="card product" style="width: 18rem">
  <div class="card-body text-center">
    <h2 class="card-title fw-bolder">TEST</h2>
    <p class="card-text fw-bolder">TEST</p>
  </div>
</div>

      <div
        class="offcanvas offcanvas-bottom"
        tabindex="-1"
        id="offcanvasBottom"
      >
        <div class="offcanvas-header">
          <button
            type="button"
            class="btn-close text-reset"
            data-bs-dismiss="offcanvas"
            aria-label="Close"
          ></button>
        </div>
        <div class="offcanvas-body">
         BODY
        </div>
      </div>

Answer №1

The issue lies in the propagation of the card click event to inner elements. To resolve this, utilize event.stopPropagation()...

const products = document.getElementsByClassName("product");
var myOffcanvas = document.getElementById('offcanvasBottom')
    
var productClick = function (event) {
    //event.preventDefault()
    event.stopPropagation()
    var bsOffcanvas = new bootstrap.Offcanvas(myOffcanvas)
    bsOffcanvas.show()
}

Array.from(products).forEach(function (element) {
    element.addEventListener("click", productClick);
})
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="98faf7f7ecebeceaf9e8d8adb6a8b6a8b5fafdecf9ab">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c6cbcbd0d7d0d6c5d4e4918a948a9489c6c1d0c597">[email protected]</a>/dist/js/bootstrap.bundle.min.js" integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf" crossorigin="anonymous"></script>


<div class="card product" style="width: 18rem">
  <div class="card-body text-center">
    <h2 class="card-title fw-bolder">TEST</h2>
    <p class="card-text fw-bolder">TEST</p>
  </div>
</div>

      <div
        class="offcanvas offcanvas-bottom"
        tabindex="-1"
        id="offcanvasBottom"
      >
        <div class="offcanvas-header">
          <button
            type="button"
            class="btn-close text-reset"
            data-bs-dismiss="offcanvas"
            aria-label="Close"
          ></button>
        </div>
        <div class="offcanvas-body">
         BODY
        </div>
      </div>

Answer №2

Include the 'show' CSS class in the offcanvas element

<div class="offcanvas offcanvase-bottom show"></div>

Alternatively, you can use JavaScript to add the class dynamically

<div class="offcanvas offcanvase-bottom show" id="off-id"></div>
<script>
    document.getElementById('off-id').classList.add('show')
</script>

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

JavaScript callbacks are not executed synchronously

My Objective : I am attempting to initiate a payment order in the payment gateway server and then send back the order details to the client using Firebase cloud functions. This process involves utilizing firebase cloud functions. The Order() function ha ...

Choose Status Menu DiscordJS version 14

Is there a way to get help with changing the bot's status if it's not working properly? The value of the variable "statuses" is set as status, but the status itself does not change. Using client.user.setStatus('dnd'); can sometimes work ...

Center a sans-serif font vertically with exact precision while adjusting the font size

My issue is an expansion of a previous problem I mentioned in another question, which can be found here Vertically align sans-serif font precisely using jquery/css. To summarize: I am aiming to align two divs containing text, with one positioned above the ...

Following the implementation of the YITH ajax navigation filter, my jQuery scripts are no longer functioning as

I'm having trouble with using yith ajax navigation in my theme. Everything works perfectly until I click on an element to filter, at which point my jquery codes stop working. The team at yith suggests: If your product list contains JavaScript cod ...

JavaScript mouse and touch movement events (mousemove, pointermove, touchmove) are not always accurate

I'm currently working on developing a JavaScript whiteboard and have implemented the following code: let lastTimestamp = 0; const fps = 1000/60; document.addEventListener("pointermove", moveMouse, false); function moveMouse (e) { e.preve ...

Creating a wrapper class in Express JS: A step-by-step guide

I am currently developing a basic wrapper app that retrieves the following information from user requests: a) Request Date & Time b) Request URL c) Response Time This is my approach to wrapping the functionality using Express.js: var express = require(&a ...

DirectionsLight isn't functioning properly in Three.js

I attempted to add lighting in Three.js, but after updating the display, the light didn't seem to affect my cylinder. I simply copied and pasted the source code from the Three.js documentation Three.js as instructed, but to no avail. Below is the cod ...

Enhance Your Website with Bootstrap 3.0 Affix

Looking to attach a right hand column to the top of the window as you scroll using Bootstrap 3.0 and 'affix' feature. Here is the HTML for the element: <div class="col-lg-4 right-hand-bar" data-spy="affix" data-offset-top="477"> This is ...

Creating a method for a Discord Bot to communicate through a Webhook (loop)

I am looking to enhance my bot's functionality by implementing a webhook triggered by a specific command. Once activated, the webhook should send a message at regular intervals. The idea is to obtain the token and ID of the created webhook, and then ...

issue related to prototypejs event handlers and event triggering

Currently, I am in the process of learning both the prototype framework and javascript as a whole. My current task involves refactoring some existing code to generate HTML from data within a class by utilizing an event listener. Despite my efforts, I am en ...

Can you explain the relationship between HTML 5 Canvas coordinates and browser pixels?

When trying to use HTML 5 canvas as a drawing board in my application, I encountered an issue. The drawings appear at an offset from the mouse pointer. My method involves using the Jquery .offset function to determine the event's position on the canv ...

An issue has been encountered in the following module federation: `TypeError: g.useSyncExternalStore is not a function`

I encountered an error after deploying my next app with module federation: TypeError: g.useSyncExternalStore is not a function The same app works fine as a standalone application when run with yarn dev or yarn start, but it fails when using module federat ...

When it comes to retrieving values from JSON objects in JavaScript, one of two identical objects will return the expected values while the other may

I encountered a perplexing issue with two identical JSON objects. When I use JSON.stringify(obj1) == JSON.stringify(obj2), it returns true. Despite both objects being accessible and inspectable in the console, I'm facing difficulty accessing the valu ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

What is the reason for typescript's lack of a "function" type?

As a newcomer to TypeScript, I'm puzzled as to why I am unable to define an object like this: const obj: { property1: string property2: boolean property3: function } It seems that the only workaround is to use: const obj: { property1: strin ...

A guide to incorporating border radius to images within a composite image with sharp.js in Node.js

In my Node.js project, I am using the sharp library to combine a collection of images into a single image. Although I have successfully created the composite image, I now need to add a border radius to each of the images in the grid. Here is the code snip ...

Encountering unexpected fetch requests to JSON files when using getStaticProps/getStaticPaths

My webpage seems to be functioning correctly, however I have noticed that in the console there are 5, 404 errors appearing on fetch requests. It's puzzling where these errors are originating from. Interestingly, these 404 errors only occur in the pro ...

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

Get Facebook to recognize and display link previews for websites using ajax technology

It is commonly known that when copying a link from an HTML website onto Facebook, the platform will attempt to fetch available images as previews for the link. But what happens when the content is dynamically generated, such as with JavaScript? In this c ...

How can we use JavaScript to add a class to the <html> element?

What is the method to apply a class to the root element <html> in JavaScript? ...