Open a modal with a button

Description: Add a button “Open”. The click must open a modal with a title, a text and a Close button.

Hint:

  • Use data-bs-toggle="modal", data-bs-target and data-bs-dismiss="modal".

Solution

<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#ex1">Open</button>
<div class="modal fade" id="ex1" tabindex="-1" aria-labelledby="ex1Label" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h1 class="modal-title fs-5" id="ex1Label">Hello</h1>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">This is a modal.</div>
      <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button></div>
    </div>
  </div>
</div>
Live preview

const m = document.getElementById('ex1');
document.querySelector('[data-bs-toggle="modal"]').click();
await new Promise(r => setTimeout(r, 700));
console.log('open: ' + m.classList.contains('show'));
m.querySelector('.modal-footer .btn').click();
await new Promise(r => setTimeout(r, 700));
console.log('open after Close: ' + m.classList.contains('show'));
Console output (real Chrome)

open: true
open after Close: false

How it works

  • The button opens the element with the id from data-bs-target.
  • modal-dialog-centered puts the box in the vertical center.

Read Modal.


Learn more about the similar topics:
Tutorials
Bootstrap Modal
Bootstrap Collapse and Accordion
Bootstrap Carousel
Bootstrap Tooltips and Popovers
Bootstrap Offcanvas
Bootstrap Toasts
Bootstrap JavaScript: Data Attributes, API and Events
Exercises & Assignments
Open a modal with a button
Create an accordion with three items
Create a carousel with three slides
Add a tooltip to a button
Create an offcanvas sidebar which opens from the left
Interview Questions & Answers
How do you open a modal in Bootstrap?
How do you create a carousel in Bootstrap?
What are data-bs-* attributes in Bootstrap?
How do you initialize tooltips and popovers in Bootstrap 5?
What is the offcanvas component in Bootstrap?
What is Popper and why does Bootstrap need it?
How do you use the Bootstrap JavaScript API?