Last updated: Mar 5, 2024
Reading time·2 min
To change the background color on an input field, set the input field's
style.background
property to a specific color.
The backgroundColor
property changes the element's background color.
Here is the HTML for this example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <input type="text" id="first_name" /> <button id="btn">Button</button> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick(event) { const input = document.getElementById('first_name'); input.style.backgroundColor = 'green'; // 👇️ optionally change the text color // input.style.color = 'white'; });
We used the document.getElementById()
method to select the button element by
its id
.
click
event listener to a button, so every time the button is clicked, the handler function is invoked.When the button is clicked, we access the input
element and change its
background color using the style.backgroundColor
property.
To change the background color of an input field when it is empty:
input
event listener to the input field.style.backgroundColor
property to a specific color.style.backgroundColor
property to an empty string.Here is the HTML for this example.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <input type="text" id="first_name" /> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const input = document.getElementById('first_name'); input.addEventListener('input', event => { if (input.value === '') { input.style.backgroundColor = 'lime'; } else { input.style.backgroundColor = ''; } });
We added an oninput
event to the input
field. The event gets triggered every
time the value of the input field changes.
If the value is not empty, we reset the backgroundColor
property.
You might see examples that use the onchange
event instead of oninput
.
The difference between the two is that oninput
gets triggered immediately
after the value has changed, whereas onchange
occurs when the element loses
focus.
I've also written an article on how to change the background color on click.
You can learn more about the related topics by checking out the following tutorials: