Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

ปิด Modal Window เมื่อคลิกนอกพื้นที่ ด้วย Vanilla JavaScript

เรียนรู้วิธีปิด modal window หรือ UI element ใดๆ เมื่อผู้ใช้คลิกนอกพื้นที่ ด้วย Vanilla JavaScript

Modal popups น่ารำคาญ โดยเฉพาะที่ครอบจอทั้งหน้า ยิ่งน่ารำคาญเมื่อโผล่มาภายในไม่กี่วินาทีหลังเข้าเว็บ — เป็น UX design ที่แย่

บางเว็บทำให้แย่กว่า: ปุ่มปิด (X) เล็กและวางตำแหน่งแปลกๆ จนคุณโกรธจนลืมว่ามาทำไม

มาแก้ไขกัน

HTML: Modal Window เรียบง่าย

เพิ่มโค้ดนี้ใน HTML document:

<main>
  <div class="modal">
    <button class="button-close-modal">X</button>
    <h2>Subscribe to my Newsletter</h2>
    <p>Get access to exclusive content that only share with my email list</p>
    <label for="email">Enter your email:</label>
    <input type="email" id="email" name="email" />
  </div>
</main>

CSS: สไตล์ Modal และ ปุ่ม

.modal {
  padding: 2rem;
  border: 1px solid #eee;
  width: max-content;
  position: fixed;
  right: 0;
  bottom: 0;
  max-width: 100%;
}
.button-close-modal {
  display: block;
  font-size: 2rem;
  font-weight: bold;
  margin-left: auto;
}

JavaScript: ตรวจจับการคลิกทั้งหมดบน Document

โค้ด JavaScript ต่อไปนี้จะปิด modal หากผู้ใช้คลิกปุ่ม X หรือ คลิกนอก modal:

document.addEventListener("click", function(event) {
  // ถ้าคลิกปุ่ม X หรือ คลิกนอก modal ให้ปิดโดยเรียก closeModal()
  if (event.target.matches(".button-close-modal") || !event.target.closest(".modal")) {
    closeModal();
  }
}, false);

function closeModal() {
  document.querySelector(".modal").style.display = "none";
}

ดูโค้ดทั้งหมดที่นี่

สิ่งที่เกิดขึ้นในโค้ด:

  • ตั้ง click event listener บน object document — ทุกการคลิกที่หน้า HTML จะถูกล็อก และรันฟังก์ชันใน curly braces
  • กำหนด 2 เงื่อนไขปิด modal: คลิกปุ่ม หรือ คลิกนอก modal
  • ใน if statement ระบุว่า "ถ้า target ตรงกับปุ่ม (matches('.button-close-modal')) หรือ (||) target ไม่ได้อยู่ใน modal (!event.target.closest('.modal')) ให้เรียก closeModal()"
  • เมื่อ closeModal() ถูกเรียก จะ select คลาส .modal และซ่อนด้วย display = 'none'

เมธอด closest() ค้นหา parent element ที่ใกล้ที่สุดซึ่งมี selector ที่ระบุ (ในที่นี้คือ .modal)

เมธอด matches() ตรวจสอบว่า event.target ตรงกับ selector ที่ระบุหรือไม่ (ในที่นี้คือคลาสปุ่มปิด .button-close-modal)