Change the background color of an Input Field using JS

avatar

Borislav Hadzhiev

Wed Dec 29 20212 min read

banner

Photo by Joshua Earle

Table of Contents #

  1. Change the background color of an Input field
  2. Change the background color when an Input field is Empty

Change the background color of an Input field #

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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </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.

index.js
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 added a click event listener to a button, which invokes a function every time the button is clicked.

When the button is clicked, we access the input element and change it's background color using the style.backgroundColor property.

Change the background color when an Input field is Empty #

To change the background color of an input field when it is empty:

  1. Add a input event listener to the input field.
  2. Check if the input's value is empty.
  3. If it is, set the style.backgroundColor property to a specific color.
  4. Otherwise, set the style.backgroundColor property to an empty string.

Here is the HTML for this example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" /> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
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 is changed.

Each time we check if the input's value is empty and if it is we update the element's background color.

On the other hand, 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.
Use the search field on my Home Page to filter through my more than 1,000 articles.