Sử dụng thuộc tính autofocus
Thuộc tính autofocus là thuộc tính Boolean (true/false) của HTML5. Khi có mặt, phần tử <input>, <textarea>, hoặc <select> sẽ tự động nhận focus khi trang tải xong.
Cú pháp cơ bản
<input type="text" name="username" autofocus> <textarea autofocus></textarea> <select autofocus><option>...</select>
Ví dụ hoàn chỉnh
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<title>Demo Autofocus</title>
<style>
form { max-width: 400px; margin: 2rem auto; padding: 1.5rem; border: 1px solid #ddd; border-radius: 8px; }
.form-group { margin-bottom: 1rem; }
label { display: block; margin-bottom: 0.5rem; font-weight: 500; }
input, select { width: 100%; padding: 0.75rem; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; }
input:focus { outline: none; border-color: #3498db; box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.2); }
button { padding: 0.75rem 1.5rem; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; }
</style>
</head>
<body>
<form action="/submit" method="POST">
<div class="form-group">
<label for="name">Họ tên (tự động focus):</label>
<input type="text" id="name" name="name" autofocus required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="subject">Chủ đề:</label>
<select id="subject" name="subject">
<option value="">-- Chọn chủ đề --</option>
<option value="support">Hỗ trợ kỹ thuật</option>
<option value="sales">Tư vấn bán hàng</option>
<option value="feedback">Phản hồi</option>
</select>
</div>
<button type="submit">Gửi</button>
</form>
</body>
</html>
Lưu ý quan trọng
- Chỉ một phần tử trên trang được có
autofocus(trình duyệt sẽ ưu tiên phần tử đầu tiên) - Không hoạt động nếu người dùng đã tương tác với trang trước khi tải xong
- Có thể bị chặn bởi cài đặt trình duyệt hoặc extension (như uBlock Origin)
- Trên mobile, bàn phím ảo có thể không tự động hiện ra
Phương pháp thay thế bằng JavaScript
Nếu cần kiểm soát linh hoạt hơn (ví dụ: focus sau khi modal mở, hoặc điều kiện cụ thể):
// Focus khi DOM ready
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('myInput').focus();
});
// Focus sau khi mở modal (Bootstrap 5 example)
const myModal = document.getElementById('myModal');
myModal.addEventListener('shown.bs.modal', function() {
document.getElementById('modalInput').focus();
});
// Focus có điều kiện
if (someCondition) {
document.querySelector('input[name="priority"]').focus();
}
Accessibility (Khả năng tiếp cận)
Sử dụng autofocus cần cân nhắc:
- Người dùng screen reader có thể bị chuyển hướng bất ngờ
- Nên dùng cho form chính của trang (login, search, đăng ký)
- Tránh dùng cho form thứ cấp hoặc popup không quan trọng