0
0
BootstrapHow-ToBeginner · 4 min read

How to Use Modal with JavaScript in Bootstrap: Simple Guide

To use a modal in Bootstrap with JavaScript, include the modal HTML structure and then create a new bootstrap.Modal instance targeting the modal element. Use methods like show() and hide() on this instance to control the modal's visibility.
📐

Syntax

The basic syntax to control a Bootstrap modal with JavaScript involves creating a modal instance and calling its methods.

  • const myModal = new bootstrap.Modal(element, options); - creates a modal instance for the given element.
  • myModal.show(); - opens the modal.
  • myModal.hide(); - closes the modal.
  • element is the modal's DOM element.
  • options is an optional object to customize behavior (e.g., backdrop, keyboard).
javascript
const myModal = new bootstrap.Modal(document.getElementById('myModal'));
myModal.show();
💻

Example

This example shows a button that opens a Bootstrap modal using JavaScript. The modal includes a header, body, and footer with a close button.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Bootstrap Modal with JavaScript</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
  <button id="openModalBtn" class="btn btn-primary">Open Modal</button>

  <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="modalLabel">Modal Title</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          This is the modal body content.
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    const modalElement = document.getElementById('myModal');
    const myModal = new bootstrap.Modal(modalElement);
    const openModalBtn = document.getElementById('openModalBtn');

    openModalBtn.addEventListener('click', () => {
      myModal.show();
    });
  </script>
</body>
</html>
Output
A webpage with a blue button labeled 'Open Modal'. Clicking it opens a centered modal with title 'Modal Title', body text, and a close button.
⚠️

Common Pitfalls

  • Not including Bootstrap's JavaScript bundle will prevent modal functionality.
  • Trying to use jQuery methods instead of Bootstrap 5's native JavaScript API causes errors.
  • Forgetting to create a bootstrap.Modal instance before calling show() or hide().
  • Using incorrect modal element selectors or IDs.
  • Not setting proper aria attributes can hurt accessibility.
javascript
/* Wrong: Trying to call show() directly on element */
document.getElementById('myModal').show(); // Error: show is not a function

/* Right: Create modal instance first */
const myModal = new bootstrap.Modal(document.getElementById('myModal'));
myModal.show();
📊

Quick Reference

Here is a quick summary of key Bootstrap modal JavaScript methods and options:

Method/OptionDescription
new bootstrap.Modal(element, options)Create modal instance for element with optional settings
show()Open the modal
hide()Close the modal
toggle()Toggle modal open/close state
dispose()Remove modal instance and event listeners
options.backdropBoolean or 'static' to control backdrop behavior
options.keyboardBoolean to enable/disable closing modal with ESC key

Key Takeaways

Always create a bootstrap.Modal instance before calling show() or hide().
Include Bootstrap's CSS and JavaScript bundle for modal functionality.
Use the modal's ID or selector correctly to target the element.
Avoid jQuery methods; use Bootstrap 5's native JavaScript API.
Set proper aria attributes for accessibility.