Bootstrap 5 Modal Via data attributes can activate a modal, by setting data-bs-toggle="modal" on an element, like a button. We can also toggle a specific modal by using a data-bs-target="#foo" or href="#foo".
Bootstrap 5 Modal Via data attributes:
- data-bs-toggle="modal": To tell the button, that we will be toggling a modal on clicking the element
- data-bs-target="#id": To tell the button, what is the id of the modal that needs to be toggled
Syntax:
<button type="button" data-bs-toggle="..."
data-bs-target="...">
...
</button>
Example 1: In this example, we will learn how to activate a modal using <button>
<!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>
<h2 class="text-success">
GeeksforGeeks
</h2>
<h3>Modal Via Attributes</h3>
<button type="button" class="btn btn-primary"
data-bs-toggle="modal"
data-bs-target="#GFG">
Using Button Attribute
</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>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Output:

Example 2: In this example, we will learn how to activate a modal using <a> tag
<!DOCTYPE html>
<html>
<head>
<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>
<h2 class="text-success">
GeeksforGeeks
</h2>
<h3>Modal Via Attributes</h3>
<a class="btn btn-primary"
data-bs-toggle="modal" href="#GFG">
Using Anchor Attribute
</a>
<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>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
Output:

References: https://getbootstrap.com/docs/5.0/components/modal/#via-data-attributes