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

การใช้งาน Event onfocusout ใน JavaScript

Event onfocusout ทริกเกอร์เมื่อ Element สูญเสีย Focus (Blur) — Bubbles (ต่างจาก onblur ที่ไม่ Bubble)

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <p>Write below:</p>
    <p>After losing focus, the background color of input check will change.</p>
    <input type="text" onfocusout="newFunc(this)">
    <script>
      function newFunc(x) {
        x.style.background = "blue";
      }
    </script>
  </body>
</html>

focusout vs blur

EventBubblesใช้เมื่อ
focusout✅ ใช่ต้องการ Event Delegation (Listen ที่ Parent)
blur❌ ไม่Listen ตรง Element เท่านั้น

รูปแบบมาตรฐานสมัยใหม่ (Delegation)

<form id="myForm">
  <input name="email" type="email">
  <input name="password" type="password">
</form>

<script>
document.getElementById('myForm').addEventListener('focusout', (e) => {
  if (e.target.matches('input')) {
    // Validate ทุก Field ที่ Blur
    if (!e.target.checkValidity()) {
      e.target.style.borderColor = 'red';
    } else {
      e.target.style.borderColor = 'green';
    }
  }
}, true); // true = Capture Phase (Optional แต่แนะนำสำหรับ Focus Events)
</script>

Focus Event Flow

focusin (Bubbles) → focus (No Bubble)
  ↓ User interacts
focusout (Bubbles) → blur (No Bubble)

ใช้ focusout เมื่อ: อยาก Validate/Track Focus Loss แบบ Delegation บน Form/Container