
In this tutorial, we will create a simple, animated, responsive modal window in plain JavaScript, HTML, and CSS.
The parent of the modal box will be animated smoothly with CSS3 transitions and transforms. It’s a nice effect that can be used for collecting user information, for error messages, for login pages, or just about anything else.
How to use it:
1. Add your content to the modal window.
<div class="modal">
<div class="modal_wrapper">
<div class="modal_content">
<div class="modal_head">
<h1 class="heading">Modal Title</h1>
</div>
<div class="modal_body">
<p>Modal Content</p>
</div>
<div class="modal_foot">
<button type="button" class="btn close_btn">Close</button>
</div>
</div>
</div>
</div>2. Create a button to toggle the modal window.
<button type="button" class="toggle_btn"> Launch </button>
3. The main JavaScript to activate the modal window.
const modals = document.querySelectorAll('.modal');
const toggleBtns = document.querySelectorAll('.toggle_btn');
const closeBtns = document.querySelectorAll('.close_btn');
const openModal = (index) => {
modals[index].classList.add('open');
};
const closeModal = (index) => {
modals[index].classList.remove('open');
};
// open the clicked Modal.
toggleBtns.forEach((currCardBtn, index) => {
currCardBtn.addEventListener('click', () => {
openModal(index);
});
});
// close the current opened Modal.
closeBtns.forEach((currCloseBtn, index) => {
currCloseBtn.addEventListener('click', () => {
closeModal(index);
});
});
// close the current opened Modal on clicking outside.
window.addEventListener('click', (e) => {
if (e.target.className === 'modal_wrapper') {
modals.forEach((currModal) => {
currModal.classList.remove('open');
});
}
});






