javascriptmodal-window

How can I make a program wait for a modal window to close?


Essentially, I'm trying to recreate the "alert" and "prompt" functions, but in a single function that uses a modal window. I have it set up so that when one of the function's parameters is set to 1, it adds a text field to the modal window and records that text field's value when it closes. I'm having trouble making it so that when the window is opened, the program waits until the window is closed again. How can I do this?


Solution

  • You need to learn how to use async and await with a promise. Basic idea below showing how the promise is used with the event handler to signal it is clicked.

    const myAlert = async(message) => {
      return new Promise((resolve) => {
        var modal = document.createElement("div");
        modal.classList.add("modal");
        modal.innerHTML = `
        <div class="modal-content">
          <span class="close">&times;</span>
          <p>${message}</p>
        </div>
      `;
        modal.querySelector(".close").addEventListener("click", function() {
          modal.remove();
          resolve();
        });
        document.body.append(modal);
      });
    
    }
    
    
    (async function() {
    
      console.log('before');
      await myAlert('Hello there');
      console.log('after');
    
    })();
    .modal {
      display: block;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgb(0, 0, 0);
      background-color: rgba(0, 0, 0, 0.4);
    }
    
    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      /* 15% from the top and centered */
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      /* Could be more or less, depending on screen size */
    }
    
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }