Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent bootstrap accordion from opening when clicking on a button on its header

I have two action buttons that are situated on the header of an a accordion like this :

enter image description here

When I click on one of these buttons, it toggles the state of the accordion. I tried e.preventDefault() and e.stopImmediatePropagation() with no success.

Here's the jsfiddle:

https://jsfiddle.net/bxzhqsad/3/

Keep in mind that I'm using Bootstrap 5.

like image 951
Jame Kayne Avatar asked Oct 18 '25 03:10

Jame Kayne


1 Answers

Here is a way to solve it:

The accordion button has the following data attribute

data-bs-collapse="collapse"

Without it, the accordion won't work. So, we can use that as a trick to disable the accordion when the mouse is over our own button.

basically saying:

on mouseenter event of your button, set the accordion button data-bs-collapse to empty string ""

on mouseleave event of your button, set the accordion button data-bs-collapse back to "collapse"

I will assume your button is a direct child of the collapse button/div, so here is some code:

yourButton.addEventListener('mouseenter', (e) => {
  let accordionButton = yourButton.parentElement;
  accordionButton.setAttribute('data-bs-toggle', '');
});

yourButton.addEventListener('mouseleave', (e) => {
  let accordionButton = yourButton.parentElement;
  accordionButton.setAttribute('data-bs-toggle', 'collapse');
});

yourButton.addEventListener('click', (e) => {
  // do whatever you want...
});

Hope this help!

like image 65
medBouzid Avatar answered Oct 20 '25 15:10

medBouzid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!