Check Bootstrap Modal is Shown using jQuery

Posted on

How to check Modal is Show or Hidden?

Bootstrap modals are one of the most popular components for displaying content in an overlay on web pages. Sometimes, developers need to know whether a modal is currently visible or hidden to perform specific actions. This article discusses various ways to check if a modal is open or not using different tools and frameworks.

1. Check If a Modal Is Open in JavaScript

For developers not using jQuery, you can use vanilla JavaScript to detect if a modal is open. Here’s an example:

document.addEventListener('DOMContentLoaded', function() {
    const modalElement = document.getElementById('myModal');
    
    modalElement.addEventListener('show.bs.modal', function() {
        alert("Modal is now open!");
    });

    modalElement.addEventListener('hide.bs.modal', function() {
        alert("Modal is now closed!");
    });
});

2. Using jQuery to Check If a Modal Is Open

Here’s an example of using jQuery to track when a modal is opened or closed:

$(document).ready(function() {
    const modal = $('#myModal');

    modal.on('show.bs.modal', function() {
        alert("Modal is now visible!");
    });

    modal.on('hide.bs.modal', function() {
        alert("Modal is now hidden!");
    });
});

Checking if a modal is open or hidden is a common task when working with modals in JavaScript or jQuery. By utilizing modal events or checking for specific classes or attributes, developers can efficiently manage modal visibility to create dynamic and interactive user experiences.