Step-by-Step Guide to Building Dynamic Modals in JavaScript Using Data Attributes
Modals are a fundamental part of modern web design, offering a sleek way to display content without redirecting users to a new page. While libraries like Bootstrap provide pre-built modal components, understanding how to create dynamic modals using JavaScript and data attributes opens up a world of possibilities for web developers. In this step-by-step guide, we'll walk through the process of building dynamic modals from scratch using JavaScript and data attributes.
Prerequisites
Before we dive in, make sure you have a basic understanding of HTML, CSS, and JavaScript. Familiarity with data attributes will be helpful but not necessary, as we'll cover them in detail.
Step 1: HTML Structure
Let's start by creating the basic HTML structure for our modal. We will use a combination of div
elements to define the modal container, content, and close button.
<!-- Modal container -->
<div class="modal" id="custom-modal">
<!-- Modal content -->
<div class="modal-content">
<!-- Modal header -->
<div class="modal-header">
<h4 class="modal-title">Modal Title</h4>
<!-- Close modal -->
<span class="close" data-modal-hide="custom-modal">×</span>
</div>
<!-- Modal body -->
<div class="modal-body">
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit.
Consectetur harum reiciendis iusto dolore maxime aliquam alias. Rem
aliquam minima excepturi.
</p>
</div>
</div>
</div>
The
div
element withid="custom-modal"
will be our modal container.The
div
element withclass="modal-content"
will be our modal content wrapper.Inside the modal header,
span
element with adata-modal-hide
attribute will be our trigger button to close the modal anddata-modal-hide
attribute's value will be our modalid
value.
Now, let's add a trigger button to open our modal.
<button class="btn-primary" data-modal-show="custom-modal">
Open Modal
</button>
We have added a data-modal-show
attribute to the button
element with our modal's id
value.
Step 2: Styling Our Modal
Add CSS to style your modal. Customize the appearance, animation, and positioning to match your design preferences. Here's a basic example to get you started:
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
}
.modal-content {
background: #fff;
border-radius: 5px;
padding: 20px;
text-align: center;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 350px;
}
.modal-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-title {
margin: 0;
font-size: 20px;
}
.close {
color: #aaa;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.modal-body {
padding-top: 5px;
font-size: 16px;
}
.btn-primary {
background-color: #008CBA;
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
border-radius: 8px;
cursor: pointer;
}
Step 3: JavaScript Functionality
As we are done with our HTML and CSS part, we will now dive into JavaScript. First, we will create two functions which responsible for opening and closing the modal.
Function: openModal()
We will wrap our modal opening operations in this function.
// Open modal function
function openModal(modalId) {
const modal = document.querySelector(`#${modalId}`);
modal.style.display = "block";
}
Parameter:
modalId
: This parameter represents theid
value of the modal that needs to be opened. It is passed to the function when calling it.
Selecting the Modal:
const modal
: This line of code usesdocument.querySelector
to select the modal element based on itsid
attribute, which matches the providedmodalId
.
Show the Modal:
modal.style.display = "block";
: This line of code makes modal visible by changing its CSS display property to'block'
.
Function: closeModal()
We will wrap our modal closing operations in this function.
// Close modal function
function closeModal(modalId) {
const modal = document.querySelector(`#${modalId}`);
modal.style.display = "none";
}
Parameter:
modalId
: This parameter represents theid
value of the modal that needs to be closed. It is passed to the function when calling it.
Selecting the Modal:
const modal
: This line of code usesdocument.querySelector
to select the modal element based on itsid
attribute, which matches the providedmodalId
.
Hide the Modal:
modal.style.display = "none";
: This line of code makes modal invisible by changing its CSS display property to'none'
.
Now, we have to call these functions when the respective trigger button is clicked.
Click Event Listener
Let's add click event listeners to the trigger buttons.
In HTML,
Elements with
data-modal-show
attribute will be trigger buttons to open the modal.Elements with
data-modal-hide
attribute will be trigger buttons to close the modal.
First, we will add an event listener to all the elements with the data-modal-show
attribute.
// Open modal when trigger button is clicked
document.querySelectorAll("[data-modal-show]").forEach((triggerButton) => {
triggerButton.addEventListener("click", () => {
const modalId = triggerButton.getAttribute("data-modal-show");
openModal(modalId);
});
});
document.querySelectorAll("[data-modal-show]")
: This part of the code selects all elements in the document that have the attributedata-modal-show
..forEach((triggerButton) => { ... })
: TheforEach
method is used to loop through all the elements selected in the previous step.triggerButton.addEventListener("click", () => { ... })
: Here we are adding aclick
event listener to the element.Inside the event listener's arrow function:
const modalId = triggerButton.getAttribute("data-modal-show");
: UsinggetAttribute()
method, we retrieved thedata-modal-show
attribute value of the element.openModal(modalId);
: At the last, we called the previously createdopenModal
function withmodalId
parameter.
We are now able to open our modals, let's add an event listener to all the elements with the data-modal-hide
attribute to hide our modals.
// Close modal when close button is clicked
document.querySelectorAll("[data-modal-hide]").forEach((closeButton) => {
closeButton.addEventListener("click", () => {
const modalId = closeButton.getAttribute("data-modal-hide");
closeModal(modalId);
});
});
document.querySelectorAll("[data-modal-hide]")
: This part of the code selects all elements in the document that have the attributedata-modal-hide
..forEach((triggerButton) => { ... })
: TheforEach
method is used to loop through all the elements selected in the previous step.triggerButton.addEventListener("click", () => { ... })
: Here we are adding aclick
event listener to the element.Inside the event listener's arrow function:
const modalId = triggerButton.getAttribute("data-modal-hide");
: UsinggetAttribute()
method, we retrieved thedata-modal-hide
attribute value of the element.closeModal(modalId);
: At the last, we called the previously createdcloseModal
function withmodalId
parameter.
Wrapping Up
Congratulations! We have successfully built dynamic modals in JavaScript using data attributes.
Checkout:
Happy Coding!