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

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

Event onfocusin ทริกเกอร์เมื่อ Element ได้รับ Focus — Bubbles (ต่างจาก onfocus ที่ไม่ Bubble)

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

<!DOCTYPE html>
<html>
  <body>
    <p>Write below:</p>
    <input type="text" onfocusin="newFunc(this)">
    <script>
      function newFunc(x) {
        x.style.background = "blue";
      }
    </script>
  </body>
</html>

focusin vs focus

EventBubblesใช้เมื่อ
focusin✅ ใช่Event Delegation (Listen ที่ Parent/Form)
focus❌ ไม่Listen ตรง Element

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

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

<script>
document.getElementById('myForm').addEventListener('focusin', (e) => {
  if (e.target.matches('input')) {
    e.target.style.background = '#e8f5e9'; // Highlight Focused Field
    e.target.select(); // Optional: Select All Text
  }
}, true); // Capture Phase สำหรับ Focus Events
</script>

Focus Event Flow

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

ใช้ focusin เมื่อ: อยาก Track/Highlight Focus แบบ Delegation บน Form/Container หลาย Field