Sobes.tech
Junior — Senior

Click handler outside the modal window

livecode

Task condition

Create an event handler that activates only when interacting outside the modal window area. This handler should call the onClose() function to close the modal window.

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>replit</title>
  <link href="style.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <style>
    .modal {
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, .5);
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .modal-content {
      background-color: #fff;
      height: 300px;
      width: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    button {
      font-size: 22px;
    }
  </style>

  <div class="modal">
    <div class="modal-content">
      <button>
        Click on me!
      </button>
    </div>
  </div>

  <script>
    function onClose() {
      console.log('Close modal')
    }

    document.addEventListener('click', function(event) {
      const modal = document.querySelector('.modal');
      if (!modal.contains(event.target)) {
        onClose();
      }
    });
  </script>
  <script src="script.js"></script>
</body>
</html>