How to prevent Bootstrap modal from closing when clicking outside?

How to prevent Bootstrap modal from closing when clicking outside?

Asked on November 1, 2018 in Bootstrap.
Add Comment


  • 1 Answer(s)

        For preventing bootstrap modal from closing when clicking outside the Modal’s backdrop Option can be used.
    When you click outside of the Bootstrap modal window i.e. on the backdrop or dark area it will close and disappear.
    It also happens when you are inside the modal and press the escape key on the keyboard.
    This can be prevented by setting the modal’s backdrop option to static and keyboard option to false.

    For example:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Disallow Bootstrap Modal from Closing</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $(".show-modal").click(function(){
            $("#myModal").modal({
                backdrop: 'static',
                keyboard: false
            });
        });
    });
    </script>
    </head>
    <body>
        <!-- Button HTML (to Trigger Modal) -->
    <input type="button" class="btn btn-lg btn-primary show-modal" value="Show Demo Modal">
     
        <!-- Modal HTML -->
        <div id="myModal" class="modal fade">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                        <h4 class="modal-title">Confirmation</h4>
                    </div>
                    <div class="modal-body">
                        <p>Do you want to save changes you made to document before closing?</p>
                        <p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Save changes</button>
                    </div>
                </div>
            </div>
        </div>
    </body>
    </html>
    
    .

    Answered on November 1, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.