Search code examples
bootstrap-modalhidebootstrap-5

Bootstrap 5 hide modal using java script


I open modal using

document.getElementById('openLoginFormBTN').addEventListener('click', function (event) {
        let loginFormModal= new bootstrap.Modal(document.getElementById('loginModal'));
          loginFormModal.show();
    });

and it works fine, but when I want to close it in function

...
console.log("user logged in")
let loginFormModal= new bootstrap.Modal(document.getElementById('loginModal'));
loginFormModal.hide();
...

It doesn't want to close.


Solution

  • I believe you can rely on the getOrCreateInstance method. No need to retreive the modal again once you have the instance.

    const btnShow = document.getElementById('openLoginFormBTN');
    const modalEl = document.getElementById('loginModal');
    const loginFormModal = bootstrap.Modal.getOrCreateInstance(modalEl);
    
    btnShow.addEventListener('click', function (event) {
        loginFormModal.show();
    });
    
    loginFormModal.hide();
    

    I created a DEMO where you can play around with this. Not sure if I've hit the mark on your use case. Please elaborate in case I missed something.