-1

https://codepen.io/yarikltv/pen/wvjrZGg here on the left side you can see the result that i want

i have old code:

<style>
.contact-us .user-box input:focus ~ label,
.contact-us .user-box input:valid ~ label{
  top: 0;
  left: 0;
  color: #17BEBE;
  font-size: 14px;
}
</style>

<div class="user-box">
 <input type="text" name="" required="">
 <label>Full name*</label>
</div>

And new code:

<div class="user-box">
  <span class="wpcf7-form-control-wrap" data-name="text-45">
    <input type="text" name="text-45" value="" size="40" class="wpcf7-form-control wpcf7-text" id="fullName" aria-invalid="false">
  </span><br>
  <label for="fullName">Full name*</label>
</div>

How to make the same effect? Maybe use JS addeventlistener or something like this.. So i need somehow replace :focus and :valid ~ label

Yaroslav
  • 59
  • 7

1 Answers1

1

Depending on your needed browser support you can use focus-within on your span element

.contact-us .user-box span:focus-within ~ label,
.contact-us .user-box span.has-input ~ label {
  top: 0;
  left: 0;
  color: #17BEBE;
  font-size: 14px;
}
let inputFields = document.querySelectorAll(".contact-us .user-box span > *")
inputFields.forEach( function(elem) {
  elem.addEventListener("blur", function() {
         if (elem.value.length >= 1){
          elem.parentNode.classList.add("has-input"); 
         } else {
          elem.parentNode.classList.remove("has-input"); 
         }
    }
  )
})
Uwe
  • 385
  • 1
  • 5
  • 14
  • yeah, it's working, but it isn't fix after :focus-within. So i need something the same with :valid, maybe with using JS. I thought about value, but it's works only after click on submit button as i understand clearly. Is any chance to do it? – Yaroslav Sep 26 '22 at 17:34
  • If it should stay that way you need to add an Event listener `onblur` and check if the value is valid and add or remove a class on the `span` element. – Uwe Sep 27 '22 at 06:42
  • I added an example in JS. We check on the length of the text and not for the validity of the input, as eg `abc@` in an email field would give back a false, as it is not a valid email address. – Uwe Sep 28 '22 at 16:47
  • Thanks a lot, it's a good experiense, i will know how to do it. Thanks!!) – Yaroslav Sep 29 '22 at 22:06