Sling Academy
Home/JavaScript/Building a Simple Modal with Pure JavaScript DOM Manipulation

Building a Simple Modal with Pure JavaScript DOM Manipulation

Last updated: December 10, 2024

Modals are a staple in web design for displaying important information without redirecting users to a different page. They are perfect for alerts, forms, and galleries. In this article, we will build a simple modal using pure JavaScript for dynamic interactions via DOM manipulation.

What is a Modal?

A modal is a component that floats over the webpage content and is typically used to grab the user's attention. It can enforce something important like getting user consent or providing additional information.

Setting Up the HTML Structure

Your first step is to establish the HTML structure. This involves defining elements for the modal, which include the overlay, the modal window, and a close button.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Modal</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <button id="openModal">Open Modal</button>

    <div class="modal hidden" id="myModal">
        <div class="modal-content">
            <span class="close-button">×</span>
            <h1>This is a Modal</h1>
            <p>You can add more content here.</p>
        </div>
    </div>

    <script src="script.js"></script>
</body>
</html>

The key parts to notice are:

  • The button with id="openModal" will trigger the opening of the modal.
  • The modal structure consists of a div with an id="myModal", which contains div.modal-content and .

Styling the Modal with CSS

Next, let's style our modal to ensure it looks appealing on the webpage.

.hidden {
    display: none;
}

.modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 10;
}

.modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    width: 80%;
    max-width: 500px;
}

.close-button {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close-button:hover,
.close-button:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

The .hidden class is used to hide the modal initially using display: none;.

Adding Interactivity with JavaScript

Now, you'll need some JavaScript to handle user interactions. This will involve opening the modal when the open button is clicked and closing it when the close button is activated.

document.addEventListener("DOMContentLoaded", function() {
    const modal = document.getElementById("myModal");
    const openModal = document.getElementById("openModal");
    const closeModal = document.querySelector(".close-button");

    openModal.addEventListener("click", function() {
        modal.classList.remove("hidden");
    });

    closeModal.addEventListener("click", function() {
        modal.classList.add("hidden");
    });

    // Close modal when clicking outside
    window.addEventListener("click", function(event) {
        if (event.target == modal) {
            modal.classList.add("hidden");
        }
    });
});

We handle specific events to control the behavior of the modal:

  • The modal is shown when the "Open Modal" button is clicked.
  • The close-button hides the modal by toggling the hidden class.
  • Clicking outside the modal content (on the modal's overlay itself) also closes the modal.

Conclusion

Modals are a useful way to display important messages to users. In this tutorial, you’ve learned how to create a simple modal using only HTML, CSS, and JavaScript. By understanding these fundamentals, you can now further customize and enhance the features of your modal according to your project needs. Modals can be enhanced with libraries for animation and additional functionality, but knowing how to build one from scratch is a valuable skill.

Next Article: Hover Effects with JavaScript: No CSS? No Problem!

Previous Article: Eavesdropping on the DOM: Using Event Bubbling & Capturing in JavaScript

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration