สร้าง Accordion (เนื้อหาขยาย/ยุบได้) ด้วย CSS สำหรับสไตล์ และ JavaScript สำหรับการ toggle
ตัวอย่างโค้ดสมบูรณ์
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> .demo { background-color: #eee; cursor: pointer; padding: 25px; width: 100%; } .active, .demo:hover { background-color: #ccc; border: 2px; font-size: 14px; } .panel { padding: 0 18px; display: none; background-color: #F0F8FF; overflow: hidden; } </style> </head> <body> <h2>Examination</h2> <p>Following is the information on exams:</p> <button class="demo">Admit Card</button> <div class="panel"> <p>Admit Card will release on 25th March.</p> </div> <button class="demo">Exam Date</button> <div class="panel"> <p>Exam will held on 30th March.</p> </div> <script> var val = document.getElementsByClassName("demo"); var i; for (j = 0; j < val.length; j++) { val[j].addEventListener("click", function() { this.classList.toggle("active"); var panel = this.nextElementSibling; if (panel.style.display === "block") { panel.style.display = "none"; } else { panel.style.display = "block"; } }); } </script> </body> </html>
คำอธิบายการทำงาน
- HTML: ปุ่ม
.demo+ เนื้อหา.panel(ซ่อนด้วยdisplay: none) - CSS: จัดสไตล์ปุ่ม, สถานะ active/hover, เนื้อหา panel
- JavaScript: Loop ทุกปุ่ม เพิ่ม click event → toggle class active + toggle panel display
ปรับปรุงสมัยใหม่ (Modern Approach):
1. ใช้ <details> & <summary> (No JS needed):
<details> <summary>Admit Card</summary> <p>Admit Card will release on 25th March.</p> </details>
2. CSS-only Accordion (ด้วย :target หรือ checkbox hack):
/* Checkbox hack */
input[type=checkbox] { display: none; }
input[type=checkbox] ~ .panel { display: none; }
input[type=checkbox]:checked ~ .panel { display: block; }
3. JavaScript แบบ Modern (ES6+):
document.querySelectorAll('.demo').forEach(btn => {
btn.addEventListener('click', () => {
btn.classList.toggle('active');
const panel = btn.nextElementSibling;
panel.style.display = panel.style.display === 'block' ? 'none' : 'block';
});
});
Accessibility (A11y) สำคัญ:
- ใช้
<button>ไม่ใช่ div (keyboard focus, screen reader) - เพิ่ม
aria-expanded="true/false" - เพิ่ม
aria-controls="panel-id"ลิงก์กับ panel - จัดการ focus management