How to create a modal with Bootstrap?

About

This page shows you how to create a modal with Bootstrap.

Limitations

No more than one modal is shown by page but you can switch between them.

You can still add an alert

Example with v4.3.1

Bootstrap uses the modal.js JQuery plugin. The structure of a modal is:

  • a root container to show and cache the content
    • a modal-dialog class container (role is document)
      • a modal-content class container
        • a modal-header class container
        • a modal-body class container
        • a modal-footer class container

Example of a Modal from Bootstrap

  • First we had bootstrap
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"/>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
  • Then we stich together the modal javascript to the HTML modal element
$('#myModal').modal({
  keyboard: true, // can we close the dialog with the touch of a key
  show: true, // do we show it when the page loads
  backdrop: true // do we see a background
})
  • Page content
<h2>Header</h2>
My Beautiful content .......
  • Modal
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="false">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="recipient-name" class="col-form-label">Recipient:</label>
            <input type="text" class="form-control" id="recipient-name">
          </div>
          <div class="form-group">
            <label for="message-text" class="col-form-label">Message:</label>
            <textarea class="form-control" id="message-text"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Send message</button>
      </div>
  </div>
  </div>
</div>
  • Result





Discover More
What is and how to create a web modal in pure HTML, Bootstrap and Jquery?

A modal is a overlay window behavior: where its contents are the only elements that can receive focus. When open, the user cannot interact with the rest of the page (nor can screen readers) until...



Share this page:
Follow us:
Task Runner