คุณสมบัติ document.activeElement คืออะไร?
คุณสมบัติ document.activeElement เป็น Read-only Property ที่ คืนค่าอิลิเมนต์ที่มี Focus อยู่ในขณะนั้น (Currently Focused Element)** ในเอกสาร
ไวยากรณ์ (Syntax)
var focusedElement = document.activeElement;
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html>
<body onclick="showActive()">
<h2>หัวข้อ 2</h2>
<p>คลิกที่อิลิเมนต์ต่างๆ เพื่อดู Active Element</p>
<input type="text" value="พิมพ์ที่นี่...">
<button>ปุ่มทดสอบ</button>
<a href="#">ลิงก์ทดสอบ</a>
<p id="output"></p>
<script>
function showActive() {
var active = document.activeElement;
var tag = active.tagName;
var id = active.id ? '#' + active.id : '';
var className = active.className ? '.' + active.className.split(' ').join('.') : '';
document.getElementById("output").innerHTML =
"Active Element: <" + tag.toLowerCase() + id + className + ">";
}
</script>
</body>
</html>
ผลลัพธ์
- คลิกที่ Input → Active Element:
<input> - คลิกที่ Button → Active Element:
<button> - คลิกที่ Link → Active Element:
<a> - คลิกที่ Body (พื้นที่ว่าง) → Active Element:
<body>
การใช้งานจริง
- ตรวจสอบว่าผู้ใช้โฟกัสอยู่ที่ช่องไหน (Form Validation UX)
- Keyboard Navigation: Trap Focus ใน Modal/Dialog
- Toolbar/Editor: รู้ว่าอิลิเมนต์ไหนโฟกัส เพื่อ Apply Formatting
- Accessibility: จัดการ Focus Management
คุณสมบัติที่เกี่ยวข้อง
| คุณสมบัติ | คำอธิบาย |
|---|---|
document.activeElement | อิลิเมนต์ที่มี Focus อยู่ (Read-only) |
document.hasFocus() | Boolean: หน้าต่างนี้มี Focus หรือไม่ (Tab Active) |
element.focus() | เมธอด: ให้ Focus แก่อิลิเมนต์ |
element.blur() | เมธอด: นำ Focus ออกจากอิลิเมนต์ |
:focus (CSS) | Pseudo-class สไตล์อิลิเมนต์ที่โฟกัส |
:focus-visible (CSS) | แสดง Focus เฉพาะ Keyboard Navigation |
จุดสำคัญ
- คืนค่า
<body>หากไม่มีอิลิเมนต์ไหนโฟกัส (หรือโฟกัสที่ body) - คืนค่า
nullหาก Document ไม่มี Focus (Tab อื่น/Minimized) - Input, Textarea, Select, Button, Anchor (href), Area, [tabindex] สามารถ Focus ได้
contenteditableelements ก็สามารถ Focus ได้