เหตุการณ์ onmouseout จะถูกกระตุ้นเมื่อเคอร์เซอร์เมาส์เคลื่อนออกจากขอบเขตขององค์ประกอบ HTML แตกต่างจาก onmouseleave ที่ไม่ทำงานเมื่อเมาส์เคลื่อนเข้า Child Elements
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body>
<h3 id="myid" onmouseout="mouseOut()" style="padding: 20px; background: #f0f0f0; display: inline-block;">
วางเมาส์ที่นี่ แล้วเคลื่อนออก
</h3>
<p>สีจะเปลี่ยนเป็นแดงเมื่อเมาส์ออกจากพื้นที่</p>
<script>
function mouseOut() {
document.getElementById("myid").style.color = "red";
}
</script>
</body>
</html>
ความแตกต่างสำคัญ: mouseout vs mouseleave
| เหตุการณ์ | Bubbling | Trigger เมื่อเมาส์เข้า Child | เหมาะสำหรับ |
|---|---|---|---|
| onmouseout | ✅ ใช่ (Bubbles) | ✅ ใช่ (ทุกครั้งที่ข้ามขอบเขต) | Tooltip, Dropdown ที่ต้องซ่อนเมื่อออกจากพื้นที่รวมลูก |
| onmouseleave | ❌ ไม่ (No Bubble) | ❌ ไม่ (เฉพาะออกจากตัวองค์ประกอบเอง) | Hover effect เรียบง่าย, ไม่ต้องการ trigger ซ้ำ |
ตัวอย่างเปรียบเทียบ
<div id="parent" style="padding: 20px; background: #eee;">
Parent
<div id="child" style="margin: 20px; padding: 20px; background: #ccc;">Child</div>
</div>
<script>
const parent = document.getElementById('parent');
// mouseout: ยิงเมื่อเข้า child และเมื่อออกจาก child/parent
parent.onmouseout = () => console.log('mouseout fired');
// mouseleave: ยิงเฉพาะเมื่อออกจาก parent จริงๆ
parent.onmouseleave = () => console.log('mouseleave fired');
</script>
การใช้งานร่วมกับ mouseover
element.onmouseover = () => element.style.background = '#e0e0e0';
element.onmouseout = () => element.style.background = ''; // คืนค่าเดิม