doe.2211 doe.2211 - 22 days ago 13
CSS Question

change label colors on floating labels

i created a floating label, wich changes the border color and the label element. my question is how to change the label color when input has some content inside?

The color should be pink when the input is focused, but when someone is typing something and click somewhere else, the color should be change back to normal

js

$('.form-control').on('focus blur', function (e) {
$(this).parents('.form-group').toggleClass('focused', (e.type === 'focus' || this.value.length > 0));
})
.trigger('blur');


css

#floating-label .form-group .form-control {
border:none;
border-bottom: 1px solid red;
border-radius: 0;
}

#floating-label .form-group {
display: flex;
height: 55px;
}

#floating-label .form-control:focus{
border-color: #FF4070;
}

#floating-label .control-label {
font-size: 1rem;
font-weight: 400;
opacity: 0.4;
pointer-events: none;
position: absolute;
transform: translate3d(6px, 22px, 0) scale(1);
transform-origin: left top;
transition: 240ms;
}

#floating-label .form-group.focused .control-label {
opacity: 1;
transform: scale(0.75);
color: #FF4070;
}

#floating-label .form-control {
align-self: flex-end;
}

#floating-label .form-control::-webkit-input-placeholder {
color: transparent;
transition: 240ms;
}

#floating-label .form-control:focus::-webkit-input-placeholder {
transition: none;
}

#floating-label .form-group.focused .form-control::-webkit-input-placeholder {
color: #bbb;
}


html

<form id="floating-label">
<div class="form-group">
<label class="control-label">Example label</label>
<input type="text" class="form-control">
</div>
<div class="form-group">
<label class="control-label">Another label</label>
<input type="text" class="form-control">
</div>
</form>


bootply

Answer

U need to change ur script to this one

$('.form-control').on('blur', function (e) {
  var parent = $(this).parents('.form-group');
  parent.removeClass('focused');
  if(this.value.length > 0) {
      parent.addClass('filled');
  }
})
.trigger('blur');

$('.form-control').on('focus', function (e) {
  var parent = $(this).parents('.form-group');
  parent.removeClass('filled');
  parent.addClass('focused');
});
Comments