By implementing the Data Attribute
Bootstrap provides the option to trigger a modal using data attributes directly in the HTML. You can add the data-bs-toggle attribute with the value modal to an element that should trigger the modal. Additionally, the data-bs-target attribute is used to specify the target modal’s id. This allows for seamless integration without the need for explicit JavaScript code.
Syntax:
<button data-bs-toggle="modal"
data-bs-target="#myModal">
Open Modal
</button>
Example: In this example, we will use data attributes for creating the modal.
<!DOCTYPE html>
<html>
<head>
<!-- Bootstrap CDN -->
<link href=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity=
"sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<script src=
"https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity=
"sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous">
</script>
</head>
<body class="w-80 p-3">
<div>
<h3>
Bootstrap Modal Via Data Attributes
</h3>
<button type="button"
class="btn btn-primary"
data-bs-toggle="modal"
data-bs-target="#GFG">
Show Modal
</button>
<div class="modal fade" id="GFG">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
Modal
</h5>
<button type="button"
class="btn-close"
data-bs-dismiss="modal">
</button>
</div>
<div class="modal-body">
<p>I am a Modal</p>
<p>
Bootstrap Modal Via Data Attributes
</p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Output:
How to Create Modal using Bootstrap?
Bootstrap modal box is a UI component that displays content overlaid on the main page. Create it by defining a trigger button with data attributes and structuring the modal in HTML with a unique ID, allowing customization of content and functionality.
Syntax:
<div class="modal"> Contents... <div>
The following approaches will be used to build the basic modal, which is described below:
Table of Content
- Using JavaScript
- By implementing the Data Attribute
- Using Bootstrap Modal Component