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>