on css i have a class that when on focus the border goes to blue, but when the user…
- User
on css i have a class that when on focus the border goes to blue, but when the user types and if there is an error I need the border to go red, but the focus border color is blocking the error one
- Assistant
To achieve the desired behavior, you can use the
:invalidpseudo-class and update the border color to red when there is an error. This way, the:focuspseudo-class will not override the error styling. Here's an example:HTML:
html<input type="text" class="input" required>CSS:
css.input:focus { border-color: blue; } .input:invalid { border-color: red; }In the above code, the
:focuspseudo-class specifies the border color as blue when the input field is in focus. The:invalidpseudo-class specifies the border color as red when the input field does not meet the specified requirements (in this case, therequiredattribute ensures that it is not left empty).Now, if the user types invalid input or leaves the field empty, the border color will change to red, irrespective of whether the input field is in focus or not.
- User
but Im also in focus when typing on the input.......
- Assistant
Apologies for the confusion. To differentiate between the focus and error states while typing, you can use JavaScript to toggle a separate error class on the input element. Here's an updated example:
HTML:
html<input type="text" class="input" required>CSS:
css.input { border: 1px solid blue; } .input:focus { border-color: blue; } .input.error { border-color: red; }JavaScript:
javascriptconst input = document.querySelector('.input'); input.addEventListener('input', function() { if (input.validity.valid) { input.classList.remove('error'); } else { input.classList.add('error'); } });In this code, the
inputevent is used to detect changes in the input value. If the input is valid, the class is removed from the input element, and if it is invalid, the class is added. The CSS styling is updated accordingly, with the class overriding the styling and setting the border color to red.