Creating a Modal in Pure JavaScript

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.


Back to Home

Table of content

Introduction

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.

What is a Modal?

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.

Basic HTML Structure

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>

Styling the Modal with CSS

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;
}

Opening and Closing the Modal with JavaScript

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';
  }
});

Enhancing the Modal Experience

  • Accessibility: Focus the modal for keyboard users, and allow pressing Esc to close it.
  • Reusable Functions: Consider turning your modal code into a reusable function or module as your project grows.
// Closing modal with keyboard Esc
window.addEventListener('keydown', (e) => {
  if (e.key === 'Escape') {
    modal.style.display = 'none';
  }
});

Conclusion

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!

Frontend
JavaScript
Modal
UI
Web Development