How to create a modal using CSS and JavaScript

Last Updated on Dec 04, 2023

modal component with header and footer

A modal in web design is a component that will pop up when it is triggered by something, such as a button click. It will disable all other components on that page, and to go back, you either have to make an action or close it. It is used when you want the user to focus on something and take an action, such as confirming to delete a record.

In this article, I will show you how to create a modal that can be triggered by a button using HTML, CSS, and JavaScript.

Without further delay, let's get started.

  1. Create the neccessary files

    Before we write our code, let's create the following files: index.html, style.css, and script.js.

  2. Create the HTML modal

    Type the following code in index.html

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>How to create a modal using CSS and JavaScript</title>
        <link rel="stylesheet" href="style.css">
      </head>
      <body>
        <!-- Start of the modal -->
        <div class="modal" id="example-modal" data-modal>
          <div class="modal-content fade" data-content="modal">
            <div class="modal-header">
              <h2>Modal Title</h2>
              <button class="modal-close" data-dismiss="modal" data-target="example-modal">&times;</button>
            </div>
            <div class="modal-body">
              <p>Text in the Modal!</p>
            </div>
            <div class="modal-footer">
              <button class="btn btn-close" data-dismiss="modal" data-target="example-modal">Close</button>
              <button class="btn btn-primary">Save</button>
            </div>
          </div>
        </div>
        <!-- End of the modal -->
    	
        <!-- Button that will trigger the modal -->
        <button class="btn btn-primary" data-toggle="modal" data-target="example-modal">Open Modal</button>
        
    	<script src="script.js"></script>
      </body>
    </html>
    
  3. In the code above, we have the modal and the button that will trigger the modal. In our button, we have data-toggle="modal", which we will use in JavaScript to select all modal buttons on a page. We also have data-target="example-modal", which will know what modal the button will trigger, so the value of data-target must be the same as the id of our modal.

    Inside our modal, we have two buttons that can close the modal. One in the header and another in the footer, both have the data-dismiss="modal" and data-target="example-modal". Similar to the previous button, data-dismiss="modal" is used to select all close buttons, while data-target is used to know which modal to close.

    In addition, we also have a data-modal attribute in our modal and a data-content="modal" in our modal content. We will use those two to close the modal when the user clicks outside the modal content.

  4. Style the modal with CSS

    Type the following code in style.css

    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    .modal {
      display: none;
      position: fixed;
      left: 0;
      top: 0;
      width: 100vw;
      height: 100vh;
      background-color: hsla(0, 0%, 20%, .5);
      z-index: 1;
      overflow: auto;
    }
    .modal-content {
      background-color: white;
      width: 50%;
      margin-top: 40px;
      margin-left: auto;
      margin-right: auto;
      border-radius: 10px;
    }
    @media screen and (max-width: 992px) {
      .modal-content {
        width: 80%;
      }
    }
    .modal-header, .modal-body, .modal-footer {
      padding: 16px;
    }
    .modal-header {
      border-bottom: 1px solid hsl(0, 0%, 80%);
      position: relative;
    }
    .modal-footer {
      border-top: 1px solid hsl(0, 0%, 80%);
      text-align: right;
    }
    .modal-close {
      color: hsl(0, 0%, 50%);
      border: none;
      background-color: white;
      font-size: 40px;
      position: absolute;
      top: 10px;
      right: 10px;
      cursor: pointer;
    }
    .btn {
      display: inline-block;
      padding: 12px 14px;
      border-radius: 5px;
      border: none;
      cursor: pointer;
    }
    .btn-close {
      background-color: hsl(0, 0%, 50%);
      color: white;
    }
    .btn-primary {
      background-color: hsl(210, 100%, 50%);
      color: white;
    }
    .d-block {
      display: block;
    }
    .fade {
      animation: fade .4s alternate;
    }
    @keyframes fade {
      from { margin-top: 0; opacity: 0% }
    }
    

    To create a modal, we need to cover all of the user's screen or viewport. To do that, we need position: fixed, left: 0, top: 0, width: 100vw, height: 100vh, and z-index: 1 in our modal. Then, we have display: none to make our modal hidden by default. We also have overflow: auto to enable scrolling in modal.

    Then we have to add modal-content at the center of the screen; to do that, we have width: 50%, margin-top: 40px, margin-left: auto, and margin-right: auto.

    After hard-refreshing the page, you will only see a button. In the next section, we will make that button work.

  5. Make the modal work with JavaScript

    Type the following code in script.js

    const modalButtons = document.querySelectorAll('[data-toggle="modal"]');
    const modalCloseButtons = document.querySelectorAll('[data-dismiss="modal"]');
    const modals = document.querySelectorAll('[data-modal]');
    
    for (const modalButton of modalButtons){
      modalButton.addEventListener('click', handleModal);
    }
    
    for (const modalCloseButton of modalCloseButtons){
      modalCloseButton.addEventListener('click', handleModal);
    }
    
    for (const modal of modals){
      modal.addEventListener('click', handleModalClick);
    }
    
    function handleModal(e) {
      modal = document.getElementById(e.target.dataset.target);
      modal.classList.toggle('d-block');
    }
      
    function handleModalClick(e) {
      modalContent = e.target.querySelector('[data-content="modal"]');
      if(modalContent != null && !modalContent.contains(e.target)) {
        modal.classList.remove('d-block');
      }
    }
    

    In the code above, we select all the modal buttons that will trigger the modal and the modal button that will close it. Then we loop through them to add a click listener, and we use the function handleModal(). The function selects the modal and toggles the d-block class.

    Then we select all modals, loop them, and add a click listener using the function handleModalClick(). The function selects the modal content and checks if the user selects outside the modal content, then removes the d-block if it is. This will close the modal when the user clicks outside of the modal-content.

    After hard-refreshing the page, you should already have a working modal.

Summary

In this tutorial, we have created a modal that can be triggered by a button and closed by clicking the close button inside the modal or by clicking outside the modal content. We have created it using HTML, CSS, and JavaScript. We can add more modals to the same page only by modifying our HTML since our JavaScript uses a loop to make all the modals work.

© John Michael Balbarona