Change backgroundcolour of input after onblur automatically across page

530 views Asked by At

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!

3

There are 3 answers

2
Tom Chung On BEST ANSWER
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.

1
David Thomas On

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:

2
japrescott On

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