How to Change the Background Color of an Input Field in JavaScript
Changing the background color of an input field is a common UI technique used to provide visual feedback to the user. You might highlight an input when a button is clicked, change its color to indicate a validation error (e.g., when it's empty), or simply update its style as part of a dynamic form.
This guide will teach you the standard methods for changing an input's background color. You will learn how to change the color in response to an external event (like a button click) and how to make the input change its own color dynamically as the user types.
Core Task: Selecting and Styling an Input
Before you can change an input's style, you must first select the element from the DOM. The document.getElementById() method is the most common way to do this. Once you have the element, you can change its background color by setting the style.backgroundColor property.
First, we need an input field and a button in our HTML, each with a unique ID.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="my-input" placeholder="Enter text here..." />
<button id="my-button">Change Color</button>
<script src="index.js"></script>
</body>
</html>
Solution 1: Change the Background Color on a Button Click
This is a common pattern where an external event triggers a style change on the input.
The logic:
- Add a
clickevent listener to the button. - Inside the event handler, select the input element.
- Set the
style.backgroundColorof the input element to your desired color.
const btn = document.getElementById('my-button');
btn.addEventListener('click', function onClick() {
const input = document.getElementById('my-input');
// Set the input's background color
input.style.backgroundColor = 'salmon';
// You can also change other styles, like the text color
input.style.color = 'white';
});
When the user clicks the button, the input field's background color will change to salmon.
Solution 2: Change the Background Color When the Input is Empty (or Valid)
A more dynamic use case is to have the input change its own color based on its current value. This is perfect for live validation feedback.
The logic:
- Add an
inputevent listener to the input field itself. This event fires every time the user types, pastes, or otherwise changes the value. - Inside the handler, check the
input.value. - If the value is empty, set one background color. Otherwise, set a different one (or reset it).
const input = document.getElementById('my-input');
input.addEventListener('input', function onInput() {
// Check if the input's value is an empty string
if (input.value.trim() === '') {
// If it's empty, set the background to a "warning" color
input.style.backgroundColor = 'lightcoral';
} else {
// If it's not empty, set it to a "valid" color (or reset it)
input.style.backgroundColor = 'lightgreen';
}
});
With this code, the input field will turn red as soon as it's empty and green as soon as the user types something into it.
Comparison of the two solutions: Event Listeners or .style Property?
addEventListener: This is the standard, modern way to handle events. It attaches a function (the "event handler") to an element that will be executed only when the specified event occurs (clickorinput)..styleProperty: Every HTML element in the DOM has a.styleproperty. This property gives you direct access to the element's inline styles. Settinginput.style.backgroundColoris the JavaScript equivalent of writing<input style="background-color: salmon;">. Note that multi-word CSS properties likebackground-colorare converted tocamelCasein JavaScript (backgroundColor).
A Note on CSS vs. Inline Styles
While setting inline styles with JavaScript works well, for more complex applications, the best practice is to toggle CSS classes instead.
.input-invalid {
background-color: lightcoral;
border-color: red;
}
.input-valid {
background-color: lightgreen;
border-color: green;
}
const input = document.getElementById('my-input');
input.addEventListener('input', function onInput() {
if (input.value.trim() === '') {
input.classList.add('input-invalid');
input.classList.remove('input-valid');
} else {
input.classList.add('input-valid');
input.classList.remove('input-invalid');
}
});
This approach is cleaner because it separates your styling (CSS) from your application logic (JavaScript).
Conclusion
Changing an input's background color is a simple but powerful technique for creating responsive user interfaces.
To do it successfully:
- Select the input element from the DOM using a method like
document.getElementById(). - Add an event listener for the event you want to react to (
clickon a button, orinputon the field itself). - Inside the handler function, modify the
.style.backgroundColorproperty of the input element based on your logic. - For more maintainable code, prefer toggling CSS classes over setting multiple inline styles.