I would like an input field to have the background colour changed after onblur. Automatically for all fields on every page. So I am hoping for a script in the header that will automatically affect all input fields.
Can this be done?
Thanks!
I would like an input field to have the background colour changed after onblur. Automatically for all fields on every page. So I am hoping for a script in the header that will automatically affect all input fields.
Can this be done?
Thanks!
It can certainly be done. Because you've demonstrated no attempt, I'm choosing to assume you're willing to support the latest/up-to-date browsers (rather than all legacy browsers):
function colorOnBlur(){
this.style.backgroundColor = '#f00';
}
var inputs = document.querySelectorAll('input');
for (var i = 0, len = inputs.length; i < len; i++){
inputs[i].addEventListener('blur', colorOnBlur);
}
Or you can add a new class-name to the elements (rather than changing the style
object yourself:
function colorOnBlur(){
this.classList.add('blurred');
}
var inputs = document.querySelectorAll('input');
for (var i = 0, len = inputs.length; i < len; i++){
inputs[i].addEventListener('blur', colorOnBlur);
}
Coupled with the CSS:
input.blurred {
background-color: #f00;
}
Obviously, adjust the relevant colours to your own tastes/requirements.
References:
since you start up in an "onblur" state, you should listen to the focus/click event, not the blur event
add css
input{ /*Blurred state*/
background-color: red;
}
.onFocus input{ /*clicked state*/
background-color: green;
}
add some javascript
$(input).
click(function(e){
body.className="onFocus";
}).
blur(function(){
body.className="";
});
document.querySelectorAll or any function returning a NodeList object can be used.