focus()
เมธอด focus() ใน JavaScript ช่วยเน้น (highlight) อีเลเมนต์ฟอร์ม HTML โดยตั้งค่าให้เป็นอีเลเมนต์ที่ใช้งานอยู่ (active element) ในเอกสารปัจจุบัน สามารถใช้กับข้อความ ปุ่ม หรืออีเลเมนต์อื่นๆ ได้
ไวยากรณ์
element.focus(options);
ตัวอย่าง
ตัวอย่างต่อไปนี้ใช้ focus() กับแท็ก anchor ที่มี id="focus" เมื่อคลิกปุ่ม จะเรียก focus() ทำให้ข้อความ "Tutorialspoint" เปลี่ยนสีเป็นแดง (ผ่าน CSS :focus)
<html> <head> <style>
a:focus, a:active {
color: red;
} </style> </head>
<body>
<a href="https://www.tutorialspoint.com/" id="focus">Tutorialspoint</a>
<input type="button" value="getfocus" onclick="getfo()">
<script>
function getfo() {
document.getElementById("focus").focus();
}
</script> </body> </html>
ผลลัพธ์
ก่อนคลิกปุ่ม: ข้อความปกติ
หลังคลิกปุ่ม: ข้อความ "Tutorialspoint" เปลี่ยนเป็นสีแดง (แสดงสถานะ focus)