Jack Man Jack Man - 6 months ago 8
CSS Question

How can I keep the original :focus element with CSS?

So, I have an

<input>
element that has the
:focus
attribute from CSS on it.

CSS

#my_input {
border: 1px solid black;
}

#my_input:focus {
border: 1px solid green;
}


This input is for a login form. If a user gets something wrong for a form, like entering less then the min characters, then the input form has a border of red. Once the error is fixed, I want the border to go back to normal. The border is turned back to normal, but now the :focus element from CSS doesn't work.

Once the user fixes the errors

JS

$("#my_input").css("border", "1px solid black");


How do you fix this problem?

Answer

By using $("#my_input").css("border", "1px solid black");, you're overwriting the CSS as you're adding that style directly to the element. Instead, use $("#my_input").css("border", ""); which will then force #my_input to use your original CSS styling.

As a quick tip, it would instead be better to do the following:

CSS

#my_input {
  border: 1px solid black;
}

#my_input:focus {
  border-color: green;
}

#my_input.error {
  border-color: red;
}

Then in your JS, to highlight the error:

$("#my_input").addClass('error');

And then to remove the error highlight:

$("#my_input").removeClass('error');