For instance, a freshly loaded form contains an <input type="text">
which has a green background colour. Once the user enters a value into the field, I would like it to be coloured blue instead.
Is it possible to accomplish this purely using CSS? I understand there is the input[type='text'][value]
selector. However, this does not reflect any changes to the form made by the user after it has finished loading, so if the form loaded with no value, it would remain unchanged regardless of what the user does.
You could give the textfield the required
attribute:
<input type="text" required />
and then check for validity with CSS:
input:invalid { background: green; }
or the opposite (only different for old browsers):
input:valid { background: blue; }
You can only do this using JavaScript. Here's an example that uses jQuery.
If you want to change the background-color
on focus
only, you can use the aptly named :focus
pseudo-selector. Here's an example of this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With