Home > Back-end >  Bootstrap 5 Static Modal Still Closes when I Click Outside
Bootstrap 5 Static Modal Still Closes when I Click Outside

Time:11-18

I am working on a page that checks if the user is currently logged in before he can do anything else. If the user is not logged in, the login modal loads and the user should not be able to do anything else unless he logs in. So far, this is what is working:

function checkrater(){
            var rater=document.getElementById("initials").value;
            if(rater.length <=0)
            {
                var myModal = new bootstrap.Modal(document.getElementById('loginModal'), {})
                myModal.toggle()
            }               
        }

and the HTML is this:

<body style="padding:5px;" onload="checkrater();">    
<div class="modal fade show" style="display: block;" id="loginModal" role="dialog" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">Please login</h5>              
              </div>
              <div class="modal-body">
                ...
              </div>
              <div class="modal-footer">                
                <button type="button" class="btn btn-primary">Login</button>
              </div>
            </div>
          </div>
        </div>

I am using bootstrap 5 for my CSS and the modal loads perfectly. My problem is when I click outside the modal, it still hides. I don't know if I did something wrong because I already tried it on another page and it still does not work. I tried it in Chrome and Firefox but got the same result.

CodePudding user response:

The issue is that you're using Bootstrap 5, but the syntax is of Bootstrap 4. All the data-* attributes of Bootstrap 4 are now data-bs-* in Bootstrap 5 to help the user identify their own data-* from Bootstrap's.

So in your code, change data-static to data-bs-static & data-keyboard to data-bs-keyboard and your code should work fine.

  • Related