The onchange event is not working in color type input with JavaScript

The onchange event works perfectly with color input elements in JavaScript. When a user selects a different color, the event triggers automatically, allowing you to capture and process the new color value.

Syntax

<input type="color" onchange="yourFunctionName(this);">

Basic Example

<!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 Event</title>
</head>
<body>
    <p>
        <label for="selectedColor">Choose Color:</label> 
        <input type="color" id="selectedColor" value="#ff0000" onchange="showValue(this);">
    </p>
    <p id="colorDisplay">Selected Color: #ff0000</p>

    <script>
        function showValue(colorInput) {
            const selectedColor = colorInput.value;
            console.log("Color changed to:", selectedColor);
            document.getElementById('colorDisplay').textContent = "Selected Color: " + selectedColor;
        }
    </script>
</body>
</html>

Using addEventListener Method

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Color Input with addEventListener</title>
</head>
<body>
    <p>
        <label for="colorPicker">Pick a Color:</label>
        <input type="color" id="colorPicker" value="#00ff00">
    </p>
    <div id="preview" style="width: 100px; height: 100px; background-color: #00ff00; border: 1px solid #000;"></div>

    <script>
        const colorPicker = document.getElementById('colorPicker');
        const preview = document.getElementById('preview');

        colorPicker.addEventListener('change', function(event) {
            const newColor = event.target.value;
            console.log("New color selected:", newColor);
            preview.style.backgroundColor = newColor;
        });
    </script>
</body>
</html>

Common Issues and Solutions

If the onchange event seems not to work, check these common issues:

Issue Solution
Function not defined Ensure your JavaScript function is declared before use
Event not firing Make sure you're actually changing the color value
Console not showing output Open browser Developer Tools (F12) to see console logs

Best Practices

For better code organization, use addEventListener instead of inline onchange attributes. This approach separates HTML structure from JavaScript behavior and allows multiple event listeners on the same element.

Conclusion

The onchange event works reliably with color input elements. Use it to capture color changes and update your interface dynamically when users select new colors.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements