how to check if bootstrap-4 modal already open?

I want to check if a certain modal is already open , I have tried this methods (bootstrap-4) but didn't work for me (always give 'false' even if the dialog is open)

 $('#myModal').data('bs.modal').isShown ;        

I checked modal classList , no any new class added to my modal after it became visible to the screen

I don't want event handlers as I don't want to track the status , I just want to check if the dialog was previously open via some other function

Answers 1

  • when a bootstrap modal (v4) is shown, as far as i can notice, three things happens in the DOM, the modal gets a two classes named fade and show respectively, and a style property with display to block (and mybe others like padding...) and the body tag gets a class named modal-open. So realy all you have to do is to check for one of those things, i recommend to check the existing of the show class.

    $('#exampleModal').hasClass('show'); // return true if the modal is open



    <!doctype html>
            <meta charset="utf-8">
            <meta http-equiv="x-ua-compatible" content="ie=edge">
            <title>Bootstrap modal</title>
            <link rel="stylesheet" href="" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">
            <script src="" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
    <script src="" integrity="sha384-alpBpkh1PFOepccYVYDB4do5UnbKysX5WZXm3XxPqe5iKTfUKjNkCk9SaVuEZflJ" crossorigin="anonymous"></script>
          <!-- Modal -->
          <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                <div class="modal-body">
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                  <button type="button" class="btn btn-primary">Save changes</button>
               setTimeout(function() {
                  var isShown = $('#myModal').hasClass('show');
               }, 1000);

Related Articles