Exercise: Creating a Modal Window with Vanilla JavaScript
Modals are a common feature in web development, used to display content in an overlay that pops up on top of the main page. They are typically used for dialogs, alerts, forms, or any content that requires the user's immediate attention. In this blog post, we will walk through how to create a simple modal window using vanilla JavaScript, HTML, and CSS.
What is a Modal Window?
A modal window is a graphical control element that temporarily blocks interaction with the main page until the user interacts with it. It's a great way to focus the user's attention on a specific task or piece of information. The modal can be closed by clicking a close button, interacting outside the modal, or pressing a key.
Implementing the Modal Window
Let’s dive into the implementation:
document.addEventListener("DOMContentLoaded", function() {
const modal = document.getElementById("myModal");
const openBtn = document.getElementById("openModal");
const closeBtn = document.getElementsByClassName("close")[0];
openBtn.onclick = function() {
modal.style.display = "block";
};
closeBtn.onclick = function() {
modal.style.display = "none";
};
window.onclick = function(event) {
if (event.target === modal) {
modal.style.display = "none";
}
};
});
Code Explanation
HTML Structure
Here’s the HTML structure that works with the JavaScript code:
<button id="openModal">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Modal content here...</p>
</div>
</div>
CSS Styling
Here’s the CSS to style the modal:
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
CSS Explanation
How It Works
Conclusion
Creating a modal window using vanilla JavaScript is a straightforward process that requires only a few lines of code. This implementation provides a basic yet functional modal that can be easily customized and integrated into any webpage. By understanding the underlying concepts, you can further enhance this modal with additional features like animations, accessibility improvements, or even converting it into a reusable component in a JavaScript framework.