I want to have animation on the lable of a input box

Viewed 26

The lable keeps showing as it's focus, I thought .num__box:not(:placeholder-shown) is the way to do it.

enter image description here

HTML:

<div class="input__box">
                
          <div>
                    <input type="number" inputmode="tel" id="ppl__join" class="num__box" min="1" max="100" name="ppl__join" placeholder="" required>
               <label class="input__lable">開放報名人數</label>
          </div>
 </div>

CSS:

  .input__lable {
      position: absolute;
      left: 10px;
      top: 8px;
      padding: 0 10px;
      color: #303245;
      font-weight: 600;
      font-size: 20px;
      cursor: text;
      transition: top 200ms ease-in,
      left 200ms ease-in;
      background-color: inherit ;
  }

  .num__box:focus + .input__lable,
  .num__box:not(:placeholder-shown) + .input__lable
  {
    position: absolute;
    top: -0.5rem;
    left: 15px;
    color: #303245;
    font-size: 18px ;
    background-color: #e3e3e3 ;
  }
1 Answers

Do you mean something like that?

const input = document.querySelectorAll('input');

input.forEach(i => {
  i.addEventListener('focusin', (e) => {
    e.target.parentElement.classList.add('focused');  
  });
  
  i.addEventListener('focusout', (e) => {    
    if (e.target.value.length === 0) {
      e.target.classList.remove('filled');
      e.target.parentElement.classList.remove('focused');
    } else {
      e.target.classList.add('filled');
    }
  });  
  
})
body { 
  background-color: #f5f5f5;
}

.form-wrapper {
  max-width: 30%;
  min-width: 300px;
  padding: 50px 30px 50px 30px;
  margin: 50px auto;   
  background-color: #ffffff;
  border-radius: 5px;
  box-shadow: 0 15px 35px rgba(50,50,93,.1),0 5px 15px rgba(0,0,0,.07);
}

.form-group {
  position:relative;  

  & + .form-group {
    margin-top: 30px;
  }
}

.form-label {
  position: absolute;
  left: 0;
  top: 10px;
  color: #999;
  background-color: #fff;
  z-index: 10;
  transition: transform 150ms ease-out, font-size 150ms ease-out;
}

.focused .form-label {
  transform: translateY(-125%);
  font-size: .75em;
}

.form-input {
  position: relative;
  padding: 12px 0px 5px 0;
  width: 100%;
  outline: 0;
  border: 0;
  box-shadow: 0 1px 0 0 #e5e5e5;
  transition: box-shadow 150ms ease-out;
  
  &:focus {
    box-shadow: 0 2px 0 0 blue;
  }
}

.form-input.filled {
  box-shadow: 0 2px 0 0 lightgreen;
}
<div class="form-wrapper">

  <form action="" class="form">
    <div class="form-group">
      <label class="form-label" for="first">開放報名人數</label>
      <input id="first" class="form-input" type="text" />
    </div>   
  </form>
  
</div>

Related