I'm using Bootstrap 5.3.2 with webpack 5.88.2. I have a bunch of popovers and some modals, and I just want all the popovers to close when a particular modal is opened so the popovers don't show up on top of the modal. Usually there should only be one popover open at a time so theoretically I should only need to close one of them, but making sure they're all closed just seems safer to me.
The modal is triggered on click of every .special-button-js, and the popover is triggered on hover of every .special-button-js. This means on mobile, both the modal and popover open on tapping .special-button-js. That probably seems weird but I want it this way. Here's my js:
import $ from 'jquery';
import { Modal, Popover } from 'bootstrap';
// using document.body and the selector option because the elements with .special-button-js are dynamically added to the DOM
const specialPopover = new Popover(document.body, {
selector: '.special-button-js',
html: true,
trigger: 'hover',
placement: 'auto',
content: function (triggerEl) {
// using content option because I need to refer to data-specialid on the .special-button-js element triggering the popover; not detailing that here
return '<div>my special popover content</div>';
}
});
const specialModalId = '#special-modal';
const specialModal = new Modal(specialModalId);
$(document).on('click', '.special-button-js', function(e) {
// also doing some stuff with data-specialid on .special-button-js here, and then...
specialModal.show();
});
document.querySelector(specialModalId).addEventListener('show.bs.modal', event => {
// my attempt at hiding all those popovers:
document.querySelectorAll('.special-button-js').forEach((el, i) => {
let popoverInstance = Popover.getOrCreateInstance(el);
popoverInstance.hide();
});
});
And my html:
<!-- basically there will be potentially hundreds of this button dynamically loaded onto the page: -->
<button type="button" class="badge text-bg-primary special-button-js" data-bs-toggle="popover" data-specialid="unique-id-here">Special Button</button>
<div class="modal fade" id="special-modal" tabindex="-1" aria-labelledby="..." aria-hidden="true">
...
</div>
The popovers and modal open and close as expected, except my attempt at hiding the popovers when the modal opens isn't working. There's no console error, it just doesn't hide the popovers. Anyone know what I'm doing wrong?
Side note: I read somewhere that $('.special-button-js').popover('hide'); might still work even though jQuery is no longer a requirement for Bootstrap, but that didn't work either.