5 Ways to Create Vanilla JS Modals

In the world of web development, modals have become an essential tool for creating engaging and interactive user experiences. A modal, also known as a dialog box or a popup, is an overlay that appears on top of the current page content, allowing users to focus on a specific task or view additional information without leaving the current page. In this article, we will explore five effective methods to create modals using plain JavaScript, also known as Vanilla JS, without relying on any external libraries.
1. The Basic Modal Structure

The foundation of any modal is its structure, which consists of two main parts: the modal itself and the trigger element that opens it. Let’s start by creating a basic HTML structure for our modal.
In the above code snippet, we have a modal container with an id of "myModal"
and a trigger button with an id of "openModal"
. The modal container includes a close button, a title, and some content. This is a simple modal structure that can be easily styled using CSS to match the desired design.
Show and Hide the Modal
To control the visibility of the modal, we can use JavaScript to toggle its display
property. Here’s a basic script to achieve this:
// Get references to the modal and trigger button elements
const modal = document.getElementById('myModal');
const openButton = document.getElementById('openModal');
// Function to show the modal
function showModal() {
modal.style.display = 'block';
}
// Function to hide the modal
function hideModal() {
modal.style.display = 'none';
}
// Add event listeners to the trigger button
openButton.addEventListener('click', showModal);
By adding an event listener to the trigger button, we can call the showModal
function when the button is clicked, making the modal visible. Similarly, we can add another event listener to the close button or any other desired element to call the hideModal
function and hide the modal.
2. Dynamic Modal Content
While static modal content is useful, sometimes we need to display dynamic content based on user interactions or specific data. Here’s how we can achieve this using JavaScript:
Step 1: HTML Structure
Let’s assume we have a list of items, and we want to display details about each item in a modal when it is clicked. Here’s our HTML structure:
- Item 1
- Item 2
- Item 3
Step 2: JavaScript Logic
We’ll use JavaScript to fetch the details of the clicked item and display them in the modal.
// Get references to the modal and item list
const dynamicModal = document.getElementById('dynamicModal');
const itemList = document.querySelector('ul');
// Get references to the item details paragraph
const itemDetails = document.getElementById('itemDetails');
// Function to show the dynamic modal with specific item details
function showDynamicModal(itemId) {
// Fetch the item details from the server or any data source
// For this example, we'll assume the item details are stored in an array
const itemDetailsData = [
{ id: 1, name: 'Item 1', description: 'Description for Item 1' },
{ id: 2, name: 'Item 2', description: 'Description for Item 2' },
{ id: 3, name: 'Item 3', description: 'Description for Item 3' },
// ...
];
// Find the details of the clicked item
const clickedItem = itemDetailsData.find(item => item.id === itemId);
// Update the modal content with the clicked item's details
itemDetails.textContent = `Name: ${clickedItem.name}\nDescription: ${clickedItem.description}`;
// Show the modal
dynamicModal.style.display = 'block';
}
// Add event listeners to the list items
itemList.addEventListener('click', event => {
if (event.target.tagName === 'LI') {
const itemId = event.target.textContent.trim();
showDynamicModal(itemId);
}
});
In this example, we fetch the item details from an array (which could be replaced with a real-world data source), find the details of the clicked item, and update the modal content with its name and description. This dynamic approach allows us to display different content in the modal based on user interactions.
3. Using CSS Transitions for Smooth Animations

Adding smooth animations to your modals can greatly enhance the user experience. CSS transitions can be used to animate the modal’s entrance and exit. Here’s how to implement them:
Step 1: CSS Setup
First, let’s set up some basic CSS styles for our modal:
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
}
.modal-content {
background-color: #fff;
padding: 20px;
border-radius: 5px;
max-width: 400px;
text-align: center;
}
Step 2: Adding Transitions
Now, let’s add CSS transitions to animate the modal’s appearance and disappearance. We’ll use the transition
property to smoothly change the opacity
and transform
values:
.modal.show {
display: flex;
opacity: 1;
transition: opacity 0.3s ease-in-out;
}
.modal.hide {
opacity: 0;
transition: opacity 0.3s ease-in-out;
}
.modal-content {
transform: scale(0.8);
transition: transform 0.3s ease-in-out;
}
.modal.show .modal-content {
transform: scale(1);
}
By applying these transitions, the modal will smoothly fade in and out, and its content will scale up and down, creating a visually appealing animation effect.
4. Handling Esc Key and Click-Away to Close Modals
It’s a good practice to provide users with multiple ways to close a modal. Let’s explore how to handle the Esc key and click-away interactions to close our modals.
Esc Key Handling
To close the modal when the user presses the Esc key, we can use the keydown
event and check if the key pressed is the Esc key:
document.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
hideModal();
}
});
Click-Away Interaction
To close the modal when the user clicks outside of it, we can add an event listener to the document and check if the clicked element is within the modal. If it’s not, we can hide the modal.
document.addEventListener('click', function(event) {
if (!modal.contains(event.target)) {
hideModal();
}
});
5. Modal with Forms and Validation
Modals are often used for form interactions, such as user registration or feedback submission. Let’s see how we can create a modal with a form and implement basic validation.
Step 1: HTML Structure
We’ll create a modal with a simple form structure:
Step 2: JavaScript Validation
We’ll use JavaScript to validate the form fields and submit the form only if all fields are filled correctly. Here’s the script:
// Get references to the modal, form, and form fields
const formModal = document.getElementById('formModal');
const form = formModal.querySelector('form');
const nameInput = document.getElementById('name');
const emailInput = document.getElementById('email');
// Function to validate the form
function validateForm() {
// Check if both fields are filled
if (nameInput.value.trim() !== '' && emailInput.value.trim() !== '') {
// Submit the form
form.submit();
} else {
// Display an error message
alert('Please fill in all required fields.');
}
}
// Add event listener to the form's submit button
form.addEventListener('submit', function(event) {
event.preventDefault(); // Prevent the default form submission behavior
validateForm(); // Call the validation function
});
In this example, we prevent the default form submission behavior using event.preventDefault()
and call our validation function. If all fields are filled, the form is submitted; otherwise, an error message is displayed.
Conclusion
Creating modals with Vanilla JS offers flexibility and control over your web applications. By following these five methods, you can implement modals with dynamic content, animations, and interactive behaviors. Remember to consider accessibility and provide clear indicators and interactions for your users. With these techniques, you can enhance the user experience and create engaging web interfaces.
Can I use external libraries for more complex modal features?
+While we focused on Vanilla JS in this article, there are popular libraries like Bootstrap or jQuery that provide pre-built modal components with advanced features. These libraries can simplify the implementation and offer additional functionalities like responsive design and accessibility enhancements.
How can I make my modals accessible for screen readers and keyboard navigation?
+To ensure accessibility, make sure your modal content is properly structured and labeled. Use aria-labelledby
and aria-describedby
attributes to associate the modal content with its title and description. Also, manage keyboard focus properly when the modal is opened, and ensure users can navigate the modal using the Tab key.
Are there any best practices for modal styling and positioning?
+When styling modals, consider using a fixed position with top: 0
and left: 0
to ensure it covers the entire viewport. Use CSS transitions and animations to create smooth effects. Additionally, consider the size and placement of your modal to ensure it’s visually appealing and doesn’t overlap important content.