Learn how to build a fully functional modal window using pure JavaScript—no frameworks or libraries required! Practical code, styling tips, and best practices included.
Table of content
Modals are essential UI components for web developers, used to display alerts, forms, or notices atop the main content. Building a modal with pure JavaScript empowers you to customize functionality and style without relying on frameworks like Bootstrap or libraries like jQuery.
A modal is a dialog or popup window layered over the main webpage. Typically, it pauses user interaction with the rest of the page until it’s dismissed.
Start by adding minimal markup for the modal and a button to trigger it:
<button id="openModal">Open Modal</button>
<div id="modal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>This is a pure JavaScript modal!</p>
</div>
</div>
For a professional look, add these CSS rules:
.modal {
display: none;
position: fixed;
z-index: 999;
left: 0;
top: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.6);
}
.modal-content {
background: #fff;
margin: 10% auto;
padding: 20px;
border-radius: 4px;
width: 300px;
position: relative;
text-align: center;
}
.close {
position: absolute;
right: 8px;
top: 8px;
font-size: 22px;
cursor: pointer;
}
Now, add JavaScript to control modal behavior:
const openBtn = document.getElementById('openModal');
const modal = document.getElementById('modal');
const closeBtn = modal.querySelector('.close');
openBtn.addEventListener('click', () => {
modal.style.display = 'block';
});
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
// Close modal when clicking outside modal-content
window.addEventListener('click', (e) => {
if (e.target === modal) {
modal.style.display = 'none';
}
});
// Closing modal with keyboard Esc
window.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
modal.style.display = 'none';
}
});
Building a modal in pure JavaScript is straightforward and gives you absolute control over its features and appearance. With these basics, you can customize and extend your modal to fit any web application on fulldev.pl and beyond!