Beginner
Beginner

Reputation: 1740

change focus color while typing in input

Suppose i have a code that validates the username

 oValidationManager.sUsername = document.getElementById('username');

 validateUsername: function () {
                oValidationManager.sUsername.addEventListener('focus', function(event){
                    oValidationManager.sUsername.style.borderColor = '#FF0000';
                    oValidationManager.sUsername.style.boxShadow = 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6)';
                });
                oValidationManager.sUsername.addEventListener('blur', function(){
                    oValidationManager.sUsername.style.borderColor = '';
                    oValidationManager.sUsername.style.boxShadow = '';
                });
                if (oValidationManager.sUsername.value === '') {
                    oValidationManager.sShowUsernameError.innerHTML = oValidationManager.aErrorMsg.username.required;
                }  else {

                    oValidationManager.sUsername.addEventListener('focus', function(event){
                        oValidationManager.sUsername.style.borderColor = '#00FF00';
                        oValidationManager.sUsername.style.boxShadow = 'inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(0, 255, 0, 0.6)';
                    });
                    oValidationManager.sShowUsernameError.innerHTML = '';
                    return true;
                }
                return false;
            },

What I want to happen is to change the focus color if the field is valid even when the user is typing. Using the code above i can get the result however I need to click somewhere to see the updated focus color it is not being updated while typing.

Upvotes: 0

Views: 854

Answers (2)

iicaptain
iicaptain

Reputation: 1195

Try doing this without event listeners. Rather than changing the css properties directly try adding and removing classes. Do your error check and if there is one add a class like .invalid to the input. Then just have a different style for that class.

CSS:

.input-field{
   border: 2px solid transparent;
}

.input-field:focus{
   border-color: blue;
}

.input-field.invalid:focus{
   border-color: red;
}

HTML:

<input type="text" class="input-field"/>

JS:

let myInput = document.querySelector(".input-field");

if(/*Something is wrong*/){
   myInput.classlist.add("invalid");
}else{
   myInput.classlist.remove("invalid");
}

Upvotes: 3

Xenio Gracias
Xenio Gracias

Reputation: 2758

input:invalid {
  background-color: red;
}
<input type="email">

Upvotes: 0

Related Questions