onchange บน <input type="color"> ทำงานเมื่อ User เลือกสีเสร็จ (ปิด Color Picker) ไม่ใช่ตอน Drag เลือก
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Color Input onchange</title>
</head>
<body>
<p>
<label for="color">Choose Color</label>
<input type="color" id="selectedColor" value="#985d5d" onchange="showValue(this);" />
</p>
<script>
function showValue(c) {
console.log("Selected color:", c.value);
document.body.style.backgroundColor = c.value; // Bonus: เปลี่ยนพื้นหลัง
}
</script>
</body>
</html>
คำอธิบาย
onchange="showValue(this)"ส่ง Element ให้ Function- Event
changeยิงเมื่อ: User เลือกสี → กด OK/ปิด Picker (Commit) - Event
inputยิง Real-time ขณะ Drag เลือกสี (Live Preview) c.valueเป็น Hex String เช่น"#ff0000"- Default Value:
value="#985d5d"
Best Practice
- ใช้
addEventListenerแทน Inline Handler input.addEventListener('input', livePreview)สำหรับ Live Previewinput.addEventListener('change', finalValue)สำหรับค่าสุดท้าย
ผลลัพธ์
เลือกสีใน Picker → กด OK → Console Log แสดง Hex Color | Body เปลี่ยนสีตามที่เลือก