[javascript] How can I trigger a Bootstrap modal programmatically?

If I go here

http://getbootstrap.com/2.3.2/javascript.html#modals

And click 'Launch demo modal' it does the expected thing. I'm using the modal as part of my signup process and there is server side validation involved. If there are problems I want to redirect the user to the same modal with my validation messages displayed. At the moment I can't figure out how to get the modal to display other than a physical click from the user. How can I launch the model programmatically?

This question is related to javascript twitter-bootstrap

The answer is


In order to manually show the modal pop up you have to do this

$('#myModal').modal('show');

You previously need to initialize it with show: false so it won't show until you manually do it.

$('#myModal').modal({ show: false})

Where myModal is the id of the modal container.


You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:

$('#myModal').modal('show');

and hide with:

$('#myModal').modal('hide');

The same thing happened to me. I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row. I used a trick to do this, Which I call the virtual button! Compatible with the latest version of Bootstrap (v5.0.0-alpha2). It might be useful for others as well.

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:

let exampleButton = document.createElement("button");
exampleButton.classList.add("d-none");
document.body.appendChild(exampleButton);
exampleButton.dataset.toggle = "modal";
exampleButton.dataset.target = "#exampleModal";

//AddEventListener to all rows
document.querySelectorAll('#exampleTable tr').forEach(row => {
    row.addEventListener('click', e => {
        //Set parameteres (clone row dataset)
        exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
        //Button click simulation
        //Now we can use relatedTarget
        exampleButton.click();
    })
});

All this is to use the relatedTarget property. (See Bootstrap docs)


HTML

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg">
  Launch demo modal
</button>

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

JS

$('button').click(function(){
$('#myModal').modal('show');
});

DEMO JSFIDDLE


If you are looking for a programmatical modal creation, you might love this:

http://nakupanda.github.io/bootstrap3-dialog/

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.


you can show the model via jquery (javascript)

$('#yourModalID').modal({
  show: true
})

Demo: here

or you can just remove the class "hide"

<div class="modal" id="yourModalID">
  # modal content
</div>

?


The following code useful to open modal on openModal() function and close on closeModal() :

      function openModal() {
          $(document).ready(function(){
             $("#myModal").modal();
          });
      }

     function closeModal () {
          $(document).ready(function(){
             $("#myModal").modal('hide');
          });  
      }

/* #myModal is the id of modal popup */


I wanted to do this the angular (2/4) way, here is what I did:

<div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
..
</div>`

Important things to note:

  • visible is a variable (boolean) in the component which governs modal's visibility.
  • show and in are bootstrap classes.

An example component & html

Component

@ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
..
@HostListener('document:keydown.escape', ['$event'])
  onEscapeKey(event: KeyboardEvent) {
    this.hideRsvpModal();
  }
..
  hideRsvpModal(event?: Event) {
    if (!event || (event.target as Element).classList.contains('modal')) {
      this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
      this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
      this.renderer.addClass(document.body, 'modal-open');
    }
  }
  showRsvpModal() {
    this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
    this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
    this.renderer.removeClass(document.body, 'modal-open');
  }

Html

<!--S:RSVP-->
<div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="niviteRsvpModalTitle">

                </h5>
                <button type="button" class="close" (click)="hideRsvpModal()" 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 bg-white text-dark"
                    (click)="hideRsvpModal()">Close</button>
            </div>
        </div>
    </div>
</div>
<!--E:RSVP-->