เรียนรู้ detect clicks นอก element — skill ที่ powerful ใช้ได้หลายสถานการณ์ เช่น ซ่อนเมนูหรือ modal windows
Basic JavaScript Outside Element Detection
สร้าง box element ใน HTML:
<div class="box">
If you click anywhere outside of me, I'm gone faster than you can snap your fingers.
</div>
Style box + สร้าง hide element utility class:
.box {
margin: 1rem auto 1rem auto;
max-width: 300px;
border: 1px solid #555;
border-radius: 4px;
padding: 1rem 1.5rem;
font-size: 1.5rem;
}
.js-is-hidden { display: none; }
JavaScript click detection:
const box = document.querySelector(".box");
document.addEventListener("click", function(event) {
if (event.target.closest(".box")) return; // คลิกใน element → do nothing
box.classList.add("js-is-hidden"); // คลิกนอก → ซ่อน!
});
JS ทำงานอย่างไร:
querySelector()หา box element → assign variableboxaddEventListener()บน document listen clicks ทั้งหน้า- User คลิก → function เริ่ม conditional statement ใน
{ .. } - คลิกใน box (
event.target.closest) →return(ไม่ทำอะไร) - คลิกนอก box → ซ่อนด้วย
classList.addเพิ่ม.js-is-hidden(display: none)
ตอนนี้คุณรู้ detect clicks นอก element แล้ว!
Wrap Up
อนาคตจะ explore click detection ลึกขึ้น สร้าง practical web component เช่น popup modal หรือ slide-in/out menu