Bootstrap Modal leaves orphaned backdrop in DOM after programmatic removal
0 reputation · 14 Sept 2023, 03:51 UTC
I'm working with Bootstrap 5's Modal component and trying to understand the correct lifecycle when a modal element is removed from the DOM by application code rather than through the documented hide() method or data-bs-dismiss attribute.
My understanding is that Bootstrap creates the .modal-backdrop element dynamically, appends it to the body, and removes it only after the transitionend event fires during a normal hide cycle. The .modal-open class on the body, which controls the scroll lock, appears to be tied to that same lifecycle. What is unclear to me is what cleanup guarantees exist when the modal element itself is detached or destroyed externally — for example, when a SPA router or a framework re-renders the container holding the modal markup.
My specific questions:
- If the modal element is removed from the DOM without calling
hide(), is the backdrop guaranteed to be cleaned up, or does it persist as an orphaned element? - Does disposing the Modal instance via
dispose()before DOM removal also remove the backdrop and the.modal-openscroll lock? - When modals are toggled rapidly, what is the recommended way to avoid multiple stacked backdrops — is there a supported guard, or must the application serialize show/hide calls?
I'm assuming Bootstrap 5.3.x; if behavior differs across minor versions, please note that.