jeudi 5 octobre 2017

Changing the colour of the input field focus using Javascript

I am implementing an html input field where the user has to enter his email address. I am also implementing validation on the same input field using javascript.

HTML Code:

<body>
    <div class="container">
        <div class="jumbotron" id="ErrorMessageJumbotron" style="display: none;">
            <div id="errorMessage">
                <i class="fa fa-exclamation-triangle fa-2x" aria-hidden="true">
                    &nbsp; &nbsp;
                    <span style="font-family: 'Poppins', sans-serif; font-weight: 500;">Please correct the marked fields.</span>
                </i>
            </div>
        </div>
    </div><!--container-->

    <div class="container jumbotron">
        <input type="text" onblur="validateEmail()" id="EmailTextbox" placeholder="E-mail address" class="form-control">
    </div>
</body>

CSS

*{
    font-family: 'Poppins', sans-serif;
}

#EmailTextbox {
    margin-bottom: 15px; 
}

input[type="text"]{
    font-size: 1em;
    height: 45px;
    width: 100%;
    border: 1px solid #949494;
}

JAVASCRIPT

function validateEmail() {
    var email = document.getElementById('EmailTextbox');
    var errorMessage = document.getElementById('ErrorMessageJumbotron');

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    if (!filter.test(email.value))
    {
        errorMessage.style.display = 'block';        
        email.style.color = '#E54A49';
        email.style.border = "1px solid #E54A49";
    }
    else {
        errorMessage.style.display = 'none';
        email.style.border = "1px solid #949494";
        email.style.color = 'black';
    }
}

If the email is incorrect, the border of the input field is set to red and the user is prompted to enter a valid email address. However, when the user clicks on the input field, the focus is coloured blue and I want it red.

I have tried several approaches to try to change the focus colour using Javascript but I did not manage to get it working properly.

Does anyone know how can I solve this please?

Thanks and much appreciated! :)




Aucun commentaire:

Enregistrer un commentaire