How to prevent the collapse action when clicking a button inside a div in Bootstrap 5 using data-bs-toggle

My div contains a data-bs-toggle attribute along with buttons.

https://i.sstatic.net/RzagX.png

When clicking on the panel, it collapses. However, I do not want this collapse event to trigger when clicking the buttons. Is there a way to control this behavior? It seems like the bs event occurs before the button click event.

I have attempted to prevent the default action and stop propagation within the click event for the buttons using the following code:

e.preventDefault();
e.stopPropagation();

Unfortunately, this did not achieve the desired effect.

Answer №1

I managed to resolve this issue by using the stopImmediatePropagation() method within the 'click' event handler of the document element.

When working with Bootstrap-5, it registers its collapse handler on the document element with the useCapture=true flag. In order to intercept the click event before it reaches the bootstrap handler, we need to register our own handler in the same manner before bootstrap does. Within our handler, we need to verify if event.target corresponds to the button (that should prevent the collapse event from occurring) and halt event propagation by invoking the event.stopImmediatePropagation() method.

This approach has proven effective for me while using bootstrap 5.3.3

<html lang="en" data-bs-theme="auto">
  <head>
    <title>Bootstrap - ignore colapse</title>
    <link href="bootstrap-5.3.3-dist/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
  
    <div id="header" data-bs-toggle="collapse" data-bs-target="#collapse-content" role="button" aria-expanded="false" aria-controls="collapse-content">
    <span>Header text - click here to show/hide content</span>
    <button id="collapse-ignore-button" class="btn btn-primary" type="button">
      Button
    </button>
    </div>
    <div class="collapse" id="collapse-content">
      <div class="card card-body">
        Content for show/hide on collapse
      </div>
    </div>

    <script>
      // Note! This code must be called BEFORE the bootstrap.bundle.min.js script included
      document.addEventListener(
        'click', 
        function(e) {
          if (e.target.id === "collapse-ignore-button") {
            // Perform an action on button click (e.g., change button color)
            e.target.classList.toggle('btn-primary');
            e.target.classList.toggle('btn-success');
            
            // Prevent other listeners from being triggered 
            e.stopImmediatePropagation();
          }
        },
        true // Attach listener to capturing phase
      );
    </script>
    
    <script src="bootstrap-5.3.3-dist/js/bootstrap.bundle.min.js" ></script>
    
  </body>
</html>

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's the best way to pass parameters through Higher-Order Components in React?

my custom component App import React, { Component } from "react"; import City from "./City"; import withDataLoader from "./withDataLoader"; const MyApp = () => { const MyCity = withDataLoader( City, "https://5e5cf5eb97d2ea0014796f01.mockapi ...

The issue of drop shadows causing links to not work properly in Internet Explorer

I am currently working on a website design that features a fixed menu positioned behind the body. When the menu icon is clicked, some jQuery code shifts the body to the left. To create the effect of the fixed menu being positioned underneath, I have added ...

Attempting to manipulate the selected tab material using a custom directive with two-way data binding

I've been struggling to change the tab using code and can't seem to figure out what's causing the error. It works fine when I use the controller to change the variable, but when trying to bind it through a directive, it breaks. var app = an ...

Exploring the concepts of arc functions in discord/js programming

Example: Having trouble understanding how to create an arc in JavaScript based on a percentage input? Here's a simple explanation: feed it a percentage and it will create an arc that represents that percentage of a circle. I've managed to get t ...

Looping through a dynamic array in Vue.js

I am working with two arrays: days:[0,1,2,3,4,5,6] and wdays:[2,3,6] My goal is to iterate through both arrays and display the output as follows: 0 : not present 1 : not present 2 : present 3 : present 4 : not present etc... The implementation should be ...

Execute AngularJS $q.all, regardless of any errors that may occur

Is there a way to ensure $q.all is triggered even if the promises return errors? I'm working on a project where I need to make multiple $http.post requests, sending user-inputted values from text fields. The backend (Django REST framework) has a valu ...

What steps can I take to avoid encountering this endless loop?

When passing foo in the arguments of useEffect to use existing array values, it causes an infinite loop because setting new values triggers the f() function again. How can this be resolved? An example of imaginary code is: const [foo, setFoo] = useState&l ...

Slideshow of table rows in HTML

On a webpage, I am populating an HTML table with a random number of rows ranging from 1 to 100. Regardless of the total number of rows, the requirement is to display only 10 rows at a time on the screen and then shift to the next set of 10 rows every 5 sec ...

Is there a way to display the back and forward buttons on a popup window opened through window.open or self.open in Chrome browser?

When I try to open a popup window using the code snippet below, I am facing some issues. self.open('myJSPPage','ServicePopUp','height=600,width=800,resizable=yes,scrollbars=yes,toolbar=yes,menubar=yes,location=yes'); Afte ...

Send a value to several PHP pages simultaneously using JQuery

I find myself asking this question due to my lack of experience. Is it possible to send a value to multiple PHP pages using JQuery? Let me illustrate what I am attempting to achieve. $(function() { $("#account").change(function() { $("#facilities" ...

What is the JavaScript method for updating an HTML5 datalist to show new options?

When populating options dynamically into an HTML5 datalist, I'm facing an issue where the browser tries to display the datalist before all the options have loaded. As a result, the list either does not show up completely or only partially shows up. Is ...

Using AngularJS to access the properties of a header within a $http request

As I navigate through the github API's pagination documentation, I am attempting to retrieve event items and extract the Link header (as recommended) in order to construct the pagination. However, I am facing difficulty in understanding how to work wi ...

I'm having trouble getting my CSS opacity to smoothly transition back to its original state of .5 using setTimeout(). What could be

I recently started learning JS, Jquery, and CSS. My goal is to create a Simon Says style game. However, when I attempt to animate the computer to automatically light up the correct square, I faced some challenges. To address this issue, I decided to star ...

Dealing with errors in React by utilizing the setState function

Encountering an issue while trying to update the state of a single component. A warning message states: Each child in an array or iterator should have a unique "key" prop. The list was created within the state. The intention is to update the list upon c ...

Sharing information between pages in React through Router

I am struggling to transfer a single string from one page to another using react router and only functional components. I have created a button that links my pages, but I can't seem to pass the string successfully. Here is an example of the code on th ...

Using ASP.NET MVC, pass a list of values separated by commas to an action method

Hey there, I'm facing an issue with an ajax call where I am trying to retrieve values from an html select multiple tag. The problem arises when I attempt to pass these values into my controller as I keep getting a null reference error in my controller ...

Tips on retrieving values from input files using jQuery

Is there a way to retrieve the value of an input type using jQuery? Specifically, when I add a file to the input file, I want to dynamically add more input types with the file's value. Currently, I am using the following code: $('#show_input&apo ...

Vue-router: I prefer to selectively choose routes for generating a dynamic loop of <router-link> components

I have successfully implemented a dynamic sidebar navigation list using router-link. <template> <div class="sidebarListItem bg-light"> <router-link v-for="route in $router.options.routes" :key="rout ...

What is the best way to change the name of a property within an object

I need to update the names of properties in a nested object. { 0: {value: "can_view"}, 1: {value: "can_create"} } The desired output should be: { user_can: "can_view", user_view: "can_create" } ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...