Bootstrap Modals

In this tutorial you will learn how to create modals with Bootstrap.

Creating Modals with Bootstrap

A modal is essentially a dialog box or popup window that serves to communicate important information to the user or prompt them to take necessary actions before proceeding. These modal windows are widely used in various scenarios, such as warning users about session timeouts or requesting final confirmations before executing critical actions like saving or deleting essential data.

Using Bootstrap's modal plugin, you can effortlessly create intelligent and flexible dialog boxes. The basic structure typically includes a header, message body, and a footer with action buttons for user interaction.

<div id="myModal" class="modal fade" tabindex="-1">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="modal-title">Confirmation</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
            <p>Do you want to save changes to this document before closing?</p>
            <p class="text-secondary"><small>If you don't save, your changes will be lost.</small></p>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-primary">Save changes</button>
        </div>
    </div>
</div>
</div>

By clicking the "Show Modal" button, the modal windows in the aforementioned instance is opened. For a better understanding, let's go through each component of this modal code individually.

  • The .modal-dialog class is responsible for setting the width, horizontal, and vertical alignment of the modal box.
  • The .modal-content class handles the styles, such as text and background color, borders, and rounded corners.
  • The .modal-header element is responsible for defining the header of the modal, usually containing a modal title and a close button.
  • The .modal-body element contains the actual content, such as text, images, forms, etc.
  • The .modal-footer element defines the footer, typically housing action buttons for the user.

Note: Additionally, the .fade class applied to the .modal element creates a fading and sliding animation effect when the modal window is shown or hidden. If a simple appearance without any effect is preferred, the .fade class can be removed. Moreover, if the modal's content becomes too long for the user's viewport or device, it will scroll independently of the page itself.

Tip: It is advisable to place the modal HTML at a top-level position in your document, preferably before the closing </body> tag, to prevent interference from other elements and ensure smooth functionality.


Activate Modals via Data Attributes

Activating a Bootstrap modal can be done simply by clicking on a button or link using data attributes, eliminating the need for custom JavaScript code. By following a specific format, you can target a specific modal to toggle.

<!-- Button HTML (to Trigger Modal) -->
<a href="#myModal" role="button" class="btn btn-lg btn-primary" data-bs-toggle="modal">Show Demo</a>

<!-- Modal HTML -->
<div id="myModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Create Header, Body, Content, and Footer for Modal -->
        </div>
    </div>
</div>

Explanation of Code

To activate a Bootstrap modal using data attributes, there are two essential components: the controller element, such as a button or link, and the modal element itself.

  • In the document, the outermost container of each modal must have a unique id (in this example, id=myModal on line no-6). This id allows it to be targeted using the data-bs-target attribute (for buttons) or href attribute (for hyperlinks) on the controller element (line no-2).
  • The data-bs-toggle=modal attribute is required on the controller element (line no-2), along with data-bs-target=#myModal or href=#myModal to specify the specific modal to toggle.

Activate Modals via JavaScript

Modal activation can also be achieved via JavaScript by calling the modal() method with the modal's unique identifier or class selector.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myModal").modal("show");
    });
});
</script>

<!-- Button HTML (to Trigger Modal) -->
<button type="button" id="myBtn" class="btn btn-lg btn-primary">Show Demo</button>

<!-- Modal HTML -->
<div id="myModal" class="modal fade" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Create Header, Body, Content, and Footer for Modal -->
        </div>
    </div>
</div>

Changing the Size of Modals

Bootstrap allows you to create modals of different sizes by adding classes like .modal-sm, .modal-lg, and .modal-xl to the .modal-dialog element.

<!-- Extra Large modal -->
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#extraLargeModal">Extra Large modal</button>

<div id="extraLargeModal" class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
<!-- Create Header, Body, Content, and Footer for Modal -->
</div></div></div>

Tip: The default modal may be as wide as 500 pixels,while the extra-large, huge, and compact modals can be as wide as 300 pixels,800 pixels,and 1140 pixels,respectively.


Changing Modal Content Based on Trigger Button

To create slightly different modals with similar content, you can use modal events and data attributes. Additionally, you can center the modal or make the modal body scrollable as needed.

You can leverage modal events to create variations in modal windows based on the same HTML structure. An example demonstrates how to dynamically change the modal window's title according to the data-title attribute value of the trigger button.

<script>
$(document).ready(function () {
    $("#myModal").on("show.bs.modal", function (event) {
        // Get the button that triggered the modal
        var button = $(event.relatedTarget);

        // Extract value from the custom data-* attribute
        var titleData = button.data("title");

        // Change modal title
        $(this).find(".modal-title").text(titleData);
    });
});
</script>

Creating Vertically Centered Modal

To vertically center the modal, simply add the class .modal-dialog-centered to the .modal-dialog element. If the modal contains lengthy content, you can also apply the .modal-dialog-scrollable class to make the modal body scrollable.

<!-- Button HTML (to Trigger Modal) -->
<a href="#modalCenter" role="button" class="btn btn-primary" data-bs-toggle="modal">Vertically Centered Modal</a>

<!-- Button HTML (to Trigger Modal) -->
<a href="#modalScrollableCenter" role="button" class="btn btn-primary" data-bs-toggle="modal">Vertically Centered Scrollable Modal</a>

<!-- Modal HTML -->
<div id="modalCenter" class="modal fade" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
<!-- Create Header, Body, Content, and Footer for Modal -->
</div></div></div>

<div id="modalScrollableCenter" class="modal fade" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
<!-- Create Header, Body, Content, and Footer for Modal -->
</div></div></div>

Using the Grid inside Modals

For more complex layouts within the modal, the Bootstrap grid system can be utilized. You can use the .row class to create rows and the .col-, .col-sm-, .col-md-, .col-lg-, and .col-xl-* classes to arrange columns within the .modal-body. An example showcases this feature.

<div class="modal-body">
<div class="row">
<div class="col-6">
    <div class="mb-3">
        <label class="form-label">First Name</label>
        <input type="text" class="form-control">
    </div>
</div></div></div>                

Loading Content in Modal via Ajax

To load content from a remote file into the Bootstrap modal, Ajax can be employed. Using the jQuery load() method and the Bootstrap show.bs.modal event, the content inside the modal body will be inserted upon activation. A sample code snippet demonstrates this functionality.

<script>
$(document).ready(function () {
    $("#myModal").on("show.bs.modal", function () {
        // Place the returned HTML into the selected element
        $(this).find(".modal-body").load("sample.htm");
    });
});
</script>

Tip: In the modals, you may also add tooltips and popovers as necessary. Any tooltips and popovers contained inside modal windows are similarly discarded when they are closed.


Bootstrap Modal Options

Customizing the behavior of a modal can be achieved by passing options to the modal() Bootstrap method. These options can be specified using data attributes or JavaScript.

For setting modal options via data attributes, append the option name to data-bs-, such as data-bs-backdrop=static and data-bs-keyboard=false, among others. While data attributes provide a convenient way to set modal options, using JavaScript is often preferred to avoid redundancy.

  • backdrop: contains a modal-backdrop elements (a black overlay region). As an alternative, you may provide static for a background to prevent the modal from closing on click.
  • keyboard: When the escape key is pressed, the modal windows closes.
  • focus: when started, centers the emphasis on the modal.
  • show: when activated or configured, displays the modal.

Data attributes offer a simple method for configuring the modal choices, but JavaScript is the better alternative because it spares you from doing repetitive effort. To learn how to configure the options for modals utilizing JavaScript, see the passing options instances in the methods section below.

In the example provided, the backdrop option is set to static (line no-5), preventing the modal from closing when clicking outside of it, i.e., the black overlay area.

<!-- By Data Attributes -->
<div id="myModal" class="modal fade" data-bs-backdrop="static" tabindex="-1">
</div>

<!-- By Javascript or jQuery -->

<script>
$(document).ready(function () {
    // Passing option
    $("#myModal").modal({
        backdrop: "static"
    });

    // Show modal
    $("#myBtn").click(function () {
        $("#myModal").modal("show");
    });
});
</script>

Bootstrap Modal Methods

Here are the standard methods available for Bootstrap modals:

  • show: Manually opening a modal window.
  • hide: A modal window may be manually hidden.
  • toggle: You may manually toggle (show and/or hide) a modal window using this technique.
  • dispose: Destroys the modal and removes it from the DOM.

Passing options

In addition, you have the option to pass options using an options object.

For instance, you can prevent the modal from closing when a user clicks on the backdrop (the black overlay area behind the modal) with the following example.

<script>
                    $(document).ready(function () {
                        // Passing option
                        $("#myModal").modal({
                            backdrop: "static"
                        });

                        // Show modal
                        $("#myBtn").click(function () {
                            $("#myModal").modal("show");
                        });
                    });
</script>

The next instance will stop the modal from closing when the escape key is used.

<script>
                    $(document).ready(function () {
                        // Passing option
                        $("#myModal").modal({
                            keyboard: false
                        });

                        // Show modal
                        $("#myBtn").click(function () {
                            $("#myModal").modal("show");
                        });
                    });
</script>

toggle

You may manually toggle a modal window using this technique.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myModal").modal("toggle");
    });
});
</script>

show

Manually opening a modal window is possible using this technique.

<script>
$(document).ready(function () {
    $("#myBtn").click(function () {
        $("#myModal").modal("show");
    });
});
</script>

hide

A modal window may be manually hidden using this technique.

<script>
$(document).ready(function () {
    // Show modal on page load
    $("#myModal").modal("show");

    // Hide modal on button click
    $("#myBtn").click(function () {
        $("#myModal").modal("hide");
    });
});
</script>

handleUpdate

In the event that the height of the modal increases in such a way that it gets higher than the viewport heights while it is open, this method repositions the modal to counteract the shock caused by the presence of the viewport scrollbar.

This situation is frequently illustrated by utilizing JavaScript to display hidden items within the modal or by utilizing Ajax to load material within the modal after it has been activated.

<script>
$(document).ready(function () {
    $("#showText").click(function () {
        $("#textBlock").show();
        $("#myModal").modal("handleUpdate");
    });
});
</script>

Bootstrap Modal Events

Several events for hooking into modal functionalities are included in the Bootstrap modal classes.

  • show.bs.modal: When the display instances method is used, this event is fired instantly.
  • shown.bs.modal: Once the user has been made aware of the modal, this event is dispatched. It won't allow itself be dismissed until the CSS transition is finished in its entirety.
  • hide.bs.modal: The instant the hide instances method is invoked, this event is triggered.
  • hidden.bs.modal: When the modal has finished being obscured to the user, this event is dispatched. It won't be fired until after the CSS transition has been finished in its entirety.
  • hidePrevented.bs.modal: When the modal window is displayed, its backdrop options is set to static, a click outside the modals window is made, or the keyboard options is set to false and the escape key is pressed, this event is triggered.

The user receives a warning message in this instance that follows after the modal window's fade-out transitions has finished completely.

<script>
                    $(document).ready(function () {
                        $("#myModal").on("hidden.bs.modal", function () {
                            alert("Modal window has been completely closed.");
                        });
                    });
</script>

If you attempt to close the modal by clicking the black area, the next instance will display a warning notification.

<script>
                    $(document).ready(function () {
                        $("#myModal").on("hidePrevented.bs.modal", function () {
                            alert("Modal can't be closed by clicking outside, because the backdrop option is set to static.");
                        });
                    });
</script>

Tip: For more examples on modals, such as setting vertical alignment, changing default width, embedding YouTube videos, and more, refer to the Bootstrap FAQ section.


FAQ

What is a Bootstrap Modal?

A Bootstrap Modal is a lightweight and versatile JavaScript component provided by the Bootstrap framework. It's used to display content in a pop-up dialog that appears on top of the current page, without the need for a new browser window or tab. Modals are commonly used for displaying additional information, forms, images, videos, and more, while keeping the user on the same page.

How do you create a basic Bootstrap Modal?

To create a basic Bootstrap Modal, you need to follow these steps:

  • Include the Bootstrap CSS and JavaScript files in your HTML document.
  • Create a button or an element that will trigger the modal.
  • Add a <div> element with the class modal to your HTML to define the structure of the modal.
  • Inside the modal <div>, add another <div> with the class modal-dialog, and within that, a <div> with the class modal-content.
  • Inside the modal-content <div>, you can add a modal-header, modal-body, and modal-footer for the title, content, and footer of the modal, respectively.
  • Customize the content and appearance of the modal according to your needs.

Here's a simplified example of the HTML structure for a basic Bootstrap Modal:

<!-- Button to trigger the modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Open Modal
</button>

<!-- Modal structure -->
<div class="modal" id="Div5">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal Title</h5>
        <button type="button" class="close" data-dismiss="modal">&amp;times;</button>
      </div>
      <div class="modal-body">
        <p>This is the modal content.</p>
      </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>

How can you customize the appearance of a Bootstrap Modal?

Bootstrap provides various classes that you can use to customize the appearance of a modal. Some important classes include:

  • modal-lg and modal-sm to control the size of the modal.
  • modal-header, modal-body, and modal-footer to style different sections of the modal.
  • modal-title for the title of the modal.
  • close to style the close button.
  • You can also add additional classes or custom CSS to achieve specific styling.

How do you use Bootstrap Modals for forms?

You can use Bootstrap Modals to create forms by placing your form elements within the modal-body section of the modal content. For instance, you can include input fields, checkboxes, radio buttons, etc., as you would in a regular HTML form.

How can you trigger a Bootstrap Modal using JavaScript?

If you want to trigger a Bootstrap Modal programmatically using JavaScript, you can use the following code snippet:

$('#myModal').modal('show'); // Replace 'myModal' with the ID of your modal

This code utilizes jQuery to show the modal with the given ID. Make sure you have included the jQuery library before using this code.

How can you handle events when a Bootstrap Modal is shown or hidden?

Bootstrap Modals provide event listeners that allow you to execute JavaScript code when a modal is shown or hidden. You can use the show.bs.modal and hidden.bs.modal events, respectively. Here's an example of how you can use these events:

$('#myModal').on('show.bs.modal', function () {
  // Code to execute when the modal is about to be shown
});

$('#myModal').on('hidden.bs.modal', function () {
  // Code to execute when the modal is hidden
});

How can you create multiple modals on a single page?

You can create multiple modals on a single page by duplicating the modal HTML structure for each modal and giving them unique IDs. Ensure that the data-target attribute in the trigger elements points to the corresponding modal ID. This way, each trigger will open its respective modal.

How do you close a Bootstrap Modal using JavaScript?

You can close a Bootstrap Modal using JavaScript by calling the .modal('hide') method on the modal element. Here's an example:

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

Can you prevent the closing of a modal under certain conditions?

Yes, you can prevent the closing of a modal under certain conditions by using the hide.bs.modal event and the .preventDefault() method. For example, if you want to prevent the modal from closing when a form has unsaved changes:

$('#myModal').on('hide.bs.modal', function (event) {
  if (unsavedChangesExist) {
    event.preventDefault(); // Prevent the modal from closing
    // Show a confirmation or warning to the user
  }
});

Are Bootstrap Modals accessible and mobile-friendly?

Yes, Bootstrap Modals are designed to be accessible and mobile-friendly by default. They work well on both desktop and mobile devices, adapting to various screen sizes. However, it's important to ensure that the content within the modals is also accessible and responsive.

How can you customize the animation effects of Bootstrap Modals?

Bootstrap Modals come with built-in fade-in and fade-out animations. However, you can customize these animations or even add your own animation effects using CSS. To customize the animation, you can override the default fade classes or use CSS transitions and animations. For example:

/* Customize fade-in and fade-out animations */
.modal.fade .modal-dialog {
  transition: transform 0.3s ease-out, opacity 0.3s ease-out;
}

.modal.fade.show .modal-dialog {
  transform: translate(0, 0);
  opacity: 1;
}

How can you create a modal that opens on page load?

If you want a modal to open automatically when the page loads, you can use JavaScript to trigger the modal's show method within a $(document).ready() block:

$(document).ready(function () {
  $('#myModal').modal('show');
});

How can you make a modal draggable or resizable?

To make a Bootstrap Modal draggable or resizable, you would need to use third-party libraries like jQuery UI. These libraries provide draggable and resizable functionalities that can be applied to the modal dialog element.

For making a modal draggable, you would include jQuery UI and then use its draggable() method on the modal dialog element. For making a modal resizable, you would use the resizable() method from jQuery UI.

How can you trigger a modal using a link or any HTML element other than a button?

You can trigger a Bootstrap Modal using a link or any HTML element by assigning the data-toggle and data-target attributes to that element. For instance, to open a modal with a link:

<a href="#" data-toggle="modal" data-target="#myModal">Open Modal</a>

How can you pass data from a triggering element to a modal?

You can pass data from a triggering element to a modal by utilizing the data-* attributes. Assign custom attributes to your trigger element and then access them within the modal's JavaScript code. For example:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-extra-info="example">Open Modal</button>
$('#myModal').on('show.bs.modal', function (event) {
  var button = $(event.relatedTarget); // Button that triggered the modal
  var extraInfo = button.data('extra-info'); // Access the data-* attribute value
  // Now you can use the 'extraInfo' variable within the modal
});

How can you position a Bootstrap Modal vertically and horizontally in the middle of the screen?

By default, Bootstrap Modals are vertically centered. To also center them horizontally, you can use CSS to set the left and right margins to "auto". Here's an example:

.modal {
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-dialog {
  margin: auto;
}

This CSS will help center the modal both vertically and horizontally on the screen.

Can you customize the close button in a Bootstrap Modal?

Yes, you can customize the close button in a Bootstrap Modal by modifying the HTML structure of the modal header. You can replace the default close button with a custom icon or text. For example:

<div class="modal-header">
  <h5 class="modal-title">Modal Title</h5>
  <button type="button" class="close" data-dismiss="modal" aria-label="Close">
    <span aria-hidden="true">&amp;times;</span>
  </button>
</div>

In this example, you can replace the &times; with your custom icon or text.

How can you disable the escape key from closing a Bootstrap Modal?

By default, Bootstrap Modals are dismissed when the Escape key is pressed. If you want to disable this behavior, you can use the data-keyboard attribute set to "false" in your modal trigger:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-keyboard="false">Open Modal</button>

Can you create a modal with a scrollable content area?

Yes, you can create a modal with a scrollable content area by applying a maximum height and adding the overflow-y: auto CSS property to the modal-body. This will make the content area scrollable when the content exceeds the available space. Here's an example:

.modal-body {
  max-height: 400px; /* Adjust as needed */
  overflow-y: auto;
}

How can you open a modal automatically after a certain delay?

To open a modal automatically after a delay, you can use the setTimeout() function in JavaScript. Here's an example that opens a modal after a delay of 3 seconds:

$(document).ready(function () {
  setTimeout(function () {
    $('#myModal').modal('show');
  }, 3000); // 3000 milliseconds (3 seconds)
});

How can you create a modal without the standard header and footer sections?

If you want to create a modal without the standard header and footer sections, you can simply omit those sections from the modal's HTML structure. Here's an example of a minimal modal with only a content area:

<div class="modal" id="Div6">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-body">
        <p>This is the modal content.</p>
      </div>
    </div>
  </div>
</div>

How can you prevent a modal from being closed when clicking outside of it?

By default, Bootstrap Modals can be closed by clicking outside the modal. To prevent this behavior, you can use the data-backdrop attribute set to "static" in your modal trigger:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" data-backdrop="static">Open Modal</button>

With this attribute, the user won't be able to close the modal by clicking outside of it.

How can you change the z-index of a Bootstrap Modal?

To change the z-index of a Bootstrap Modal, you can use CSS to modify the z-index property of the .modal class or the specific modal you want to adjust. For example:

.modal {
  z-index: 1050; /* Adjust the value as needed */
}

Remember that changing the z-index can impact the stacking order of elements on your page, so use it carefully.


Conclusion

Bootstrap Modal Dialogs prove to be a versatile and effective tool for presenting content and engaging users within web applications. Serving as Popup Windows, they create a dynamic and attention-grabbing user interface, enhancing the overall interactive experience. The capability for Dynamic Modal Presentation adds a layer of flexibility, allowing developers to showcase various types of content in an interactive and engaging manner. Modal Popovers extend this functionality, providing additional context and information in a user-friendly overlay.

The concept of Content Overlay with Bootstrap Modals creates a visually appealing and immersive experience, making it an ideal solution for presenting rich media and interactive forms. Modal Component Integration seamlessly incorporates the modal feature into the overall design, ensuring a cohesive and integrated user interface.

The responsiveness and adaptability of Responsive Bootstrap Modals ensure a consistent and user-friendly experience across devices. Furthermore, the availability of Customizable Modal Dialogs allows developers to tailor the appearance and behavior of modals to match the design language and branding of the web application.

User Interaction with Modals is facilitated through a combination of interactive elements, such as forms integrated into the modals, providing a smooth and intuitive user journey. The inclusion of Stylish Modals contributes to the overall aesthetic appeal, creating visually pleasing dialog boxes. The concept of Dynamic Overlay Content and Popup Dialogs further extends the versatility of Bootstrap Modals, making them suitable for a wide range of applications and content presentations.

The introduction of Vertical Layout Modals and the ability to Modify Modal Dimensions offer additional customization options, allowing developers to adapt modals to specific design requirements. Dynamic Content Injection ensures that modals can be updated dynamically, providing a dynamic and up-to-date user experience.

The activation of modals via both Data Attributes and JavaScript offers developers flexibility in choosing the method that best suits their implementation. This includes features such as Resizing Modals Dynamically, Triggering Modals via Data Attributes, and JavaScript Activation of Vertical Modals, providing developers with granular control over modal behavior.