Sự kiện ontoggle kích hoạt khi <details> thay đổi trạng thái mở/đóng (user click <summary> hoặc JS toggle open attribute).
Ví dụ
<!DOCTYPE html>
<html>
<body>
<h2>Thông tin chi tiết</h2>
<details ontoggle="display()">
<summary>Nhấn để xem thêm</summary>
<p>Giờ làm việc: 9:00 - 17:30</p>
<p>Địa chỉ: Hà Nội</p>
</details>
<script>
function display() {
const details = document.querySelector('details');
alert(details.open ? "Đã mở" : "Đã đóng");
}
</script>
</body>
</html>
Chi tiết <details> & <summary>
<details>: Container có thể mở/đóng.<summary>: Nhãn hiển thị, click để toggle (bắt buộc cho accessibility).- Thuộc tính
open: Mặc định mở. - CSS:
details[open] summary::after { content: " ▼"; }
JS kiểm soát
const d = document.querySelector('details');
d.open = true; // Mở
d.open = false; // Đóng
d.addEventListener('toggle', e => console.log(d.open ? 'open' : 'closed'));
Lưu ý
- Hỗ trợ tốt trên trình duyệt hiện đại (IE không hỗ trợ).
- Thay thế cho accordion JS đơn giản.