ret
ret

Reputation: 239

Javascript Bootstrap | Open bootstrap modal with javascript and not with button

How can we open bootstrap modal with javascript and not with button? I need to open without button, because another javascript program will decide when to open the modal.

JAVASCRIPT:

<script>
  //...
  document.getElementById("modalElement").style.visibility = ""; 
</script>

HTML:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
  Launch demo modal
</button>

<!-- Modal -->
<div id="modalElement" class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        ...
      </div>
      <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>
      </div>
    </div>
  </div>
</div>

Upvotes: 6

Views: 14995

Answers (5)

Javier Criado
Javier Criado

Reputation: 1

answer using purely javascript

    var modalElement = new bootstrap.Modal(document.getElementById('modalElement'))

https://getbootstrap.com/docs/5.0/components/modal/#via-javascript

or if your calling it asynchronously

    const modalElement = bootstrap.Modal.getOrCreateInstance('#modalElement');
    modalElement.show();

https://getbootstrap.com/docs/5.0/components/modal/#getorcreateinstance

btw. you have two id attributes there. you must have only one id attribute in your element

Upvotes: 0

Nagendra Babu
Nagendra Babu

Reputation: 1

const modalElement = document.getElementById('yourmodalid');
if(modalElement){ 
    const modal = new bootstrap.Modal(modalElement); modal.show(); 
}

Upvotes: 0

user20958373
user20958373

Reputation:

This one works for Bootstrap 5

new bootstrap.Modal(document.querySelector("#exampleModalCenter")).show();

Upvotes: 6

Phibinary
Phibinary

Reputation: 111

This is for Bootstrap 5 but should work in lower versions as well.

document.querySelector(".modal").classList.add("show");
document.querySelector(".modal").style.display = "block";

Upvotes: 3

Liad Yogev
Liad Yogev

Reputation: 874

Use .modal('show').

With jQuery it will be: $('#modalElement').modal('show')

Extracted from Bootstrap Modal API

Upvotes: 6

Related Questions