Toggle classes บน elements ด้วย JS เป็น skill practical ที่สุดสำหรับ developer ใช้สำหรับ show/hide menus, add/remove search filters, social media buttons (likes, thumbs up)

Toggle ไม่ยุ่งยาก แค่幾行 code ขึ้นกับ context วันนี้เรียนวิธีง่ายเริ่มต้น toggle และ JS ทั่วไป
HTML Structure
Setup HTML elements ก่อน: wrapper, button, box
<div class="wrapper">
<button class="button">Toggle</button>
<div class="box"></div>
</div>
Wrapper จัด center children ด้วย CSS (cosmetic)
Note: CodePen ใส่ใน HTML tab พวกเขาเพิrupa body tags ให้
CSS Style
Wrapper (.wrapper) มี Flexbox center children ไล่ละเอียดใน tutorial อื่น
Button และ box basic styling
.wrapper { padding: 2rem; display: flex; flex-direction: column; justify-content: center; align-items: center; }
.box { width: 200px; height: 200px; background-color: #eeeeee; }
.button { display: block; text-align: center; font-size: 1.5rem; color: white; background-color: #262422; border-radius: 4px; padding: 1rem 2rem; margin-bottom: 1rem; }
.bg-red { background-color: #aa2f18; }
สำคัญ: .bg-red class มี background-color #AA2F18 (แดง) — class นี้จะ toggle (เพิ่ม/ลบ) ให้ box element ตอนคลิกปุ่ม
JavaScript Event Handling
Store reference 2 elements (box, button):
let button = document.querySelector(".button");
let box = document.querySelector(".box");
Attach addEventListener() บน button listen click event → run function toggle background color:
button.addEventListener("click", function() {
box.classList.toggle("bg-red");
});
classList.toggle() ทำงาน: ถ้าคลาสมีอยู่แล้ว → ลบ ถ้าไม่มี → เพิ่ม
เสร็จแล้ว! รู้ toggle classes ด้วย plain JS CodePen มีโค้ดทั้งหมด
Compatible modern browsers from IE10+