Description
The issue I'm seeing happens when a <button>
with the data attributes data-bs-toggle="modal" data-bs-target="#modal"
is clicked first to open the modal and again to close the modal. On the second click, the modal hides then immediately shows. I've been debugging this for hours and I can't seem to figure out why on the second click the hide.bs.modal
event occurs as expected followed immediately by show.bs.modal
. It seems that the Modal.hide()
function is called followed by Modal.toggle()
. Since the modal is first hidden and then toggled (effectively hiding and showing the modal), the modal doesn't close as expected.
Here's my setup with Bootstrap V5.2. I have the following modal: <div id="modal" class="modal"></div>
which is shown when this button is clicked:
<button class="navbar__menu-toggle-button" type="button" data-bs-toggle="modal"
data-bs-target="#modal" data-target-template="#main-nav-menu" aria-label="Toggle navigation">
<span></span>
<span></span>
<span></span>
</button>
I have no additional javascript that shows/hides/toggles the modal and I'm only including Bootstrap on my WordPress site once in the theme. While debugging, I found this in the Bootstrap repo and I don't understand why lines #360-363 exist (code snippet below). Is toggle()
not designed to be used with a single modal instance?
const alreadyOpen = SelectorEngine.findOne(OPEN_SELECTOR)
if (alreadyOpen) {
Modal.getInstance(alreadyOpen).hide()
}
const data = Modal.getOrCreateInstance(target)
data.toggle(this)
When the modal is already open, these are the order of events:
click
hide.bs.modal
hidden.bs.modal
show.bs.modal
shown.bs.modal
EDIT NOTE:
Noting that when I removed the data-bs-toggle
and data-bs-target
data attributes and called modal.toggle(e.currentTarget)
when the button was clicked, the modal behaves as expected.
Working Demo:
https://codepen.io/e_aka/pen/mydGQYW