Question

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!

Was it helpful?

Solution

window.onload = function(){
  Array.prototype.slice.call(document.getElementsByTagName('input')).forEach(function(element){
    element.addEventListener('blur',function(){
        //anything here. Notice that both this and element refer to each input element.
    })
  });
}

document.querySelectorAll or any function returning a NodeList object can be used.

OTHER TIPS

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="";
    });

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);
}

JS Fiddle demo.

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;
}

JS Fiddle demo.

Obviously, adjust the relevant colours to your own tastes/requirements.

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top