Use MutationObserver to check if Bootstrap modal is open
19 May 2023 (Updated 7 July 2024)
const bodyElement = document.querySelector<HTMLBodyElement>('body')
if (!bodyElement) {
console.warn('Could not find body element')
return
}
// Create an observer instance and provide a callback function to run
// when the node is modified.
const observer = new MutationObserver(function(mutations) {
mutations.forEach((mutation) => {
const newBodyElement = mutation.target
if (!(newBodyElement instanceof HTMLBodyElement)) {
console.warn(
'Expected the mutation target to be an instance of HTMLBodyElement'
)
return
}
const hasModalOpen = newBodyElement.classList.contains('modal-open')
console.log(hasModalOpen)
})
})
// Start observing the target node for configured mutations
observer.observe(bodyElement, {
attributeFilter: ['class'],
})
Tagged:
JavaScript
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment