TerrorZero TerrorZero - 3 months ago 8
CSS Question

Changing CSS class based on JQuery Validation

I have a CSS class that provides a transition on focus of an input field combined with JQuery to validate the input. The validation works perfectly but I would also like the transition to change color on focus based on whether the input was successful or not.

this is my transition class

.bar::before {
content: '';
height: 0.125rem;
width: 0;
left: 50%;
bottom: -0.0625rem;
position: absolute;
background: #337ab7;
-webkit-transition: left 0.28s ease, width 0.28s ease;
transition: left 0.28s ease, width 0.28s ease;
z-index: 2;
}


I have tried using
.has-error
which doesn't seem to be working

.has-error .bar::before {
background: #d9534f;
left: 0;
width: 100%;
}


I have also tried using
input:invalid
but that only relates to the HTML validation and not that of the library. I have tried looking at many examples for help but I haven't been able to manage. e.g: http://formvalidation.io/examples/changing-success-error-colors/

Essentially the goal is to get the transition bar to change to red on focus of the field if the field is invalid whilst still maintaining the error messages.

Any help would be greatly appreciated :)

Answer

Here's a fiddle that I think does what you'd like: https://jsfiddle.net/ColiniloC/f9kshd1c/

HTML:

<label class='bar'>
    <input type='text' />
</label>

CSS:

.bar{
  display: inline-block;
  padding-bottom: 0.125rem;
  position: relative;
}

.bar::after{
    content: '';
    height: 0.125rem;
    width: 0;
    left: 50%;
    bottom: 0;
    position: absolute;
    background: #337ab7;
    -webkit-transition: left 0.28s ease, width 0.28s ease;
    transition: left 0.28s ease, width 0.28s ease;
    z-index: 2;
}

.bar.has-error::after{
  background: #d9534f;
  left: 0;
  width: 100%;
}

Some notable items that changed:

  1. You need to leave some space in the enclosing box for .bar::after since it's going to need that space. (Otherwise the box will jump down or if it has 'overflow: hidden' the bar won't be visible.
  2. The bar should be bottom: 0;

You might also be able to move the red colour to the bar's 'non-error' state since it's not visible anyway. (Depends on what the full effect is that you're going for.