javascriptbootstrap-modalbootstrap-5

bootstrap 5 close modal with vanilla javascript


Hello Following the tutorial here https://getbootstrap.com/docs/5.0/components/modal/#via-javascript they use a button to toggle showing the modal. And if you want to show a modal in bootstrap 5 with javascript you basically use var myModal = new bootstrap.Modal(document.getElementById('staticBackdrop')); myModal.show();

My question is how can I close a modal with javascript that was opened with the button. Basically how could I get a handle to that modal that was already opened? I realize once I had the handle I would just call .hide()

---Edit--- To make this clear. in bootstrap 5 when it is opened without using javascript

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>

I was trying to get a handle to that modal


Solution

  • Figured it out.

    var myModalEl = document.getElementById('staticBackdrop');
    var modal = bootstrap.Modal.getInstance(myModalEl)
    modal.hide();
    

    I was missing the bootstrap.Modal.getInstance. Everytime I spend 5 hours staring at something and looking for answers. I finally post here, and immediately figure it out lol.