Home > Back-end >  How do I make my javascript code for adding a new class to HTML more responsive?
How do I make my javascript code for adding a new class to HTML more responsive?

Time:04-12

<div >
  <input
    type="email"
    id="email"
    
    onblur="getValEmail()"
  />
  <label for="email">Email</label>
</div>
<div >
  <textarea id="message" onblur="getValMsg()"></textarea>
  <label for="message">message</label>
</div>



function getValEmail() {
  const valEmail = document.getElementById("email");

  valEmail.addEventListener("blur", function () {
    if (valEmail.value) valEmail.parentElement.classList.add("filled");
    else valEmail.parentElement.classList.remove("filled");
  });
}

function getValMsg() {
  const valMsg = document.getElementById("message");

  valMsg.addEventListener("blur", function () {
    if (valMsg.value) valMsg.parentElement.classList.add("filled");
    else valMsg.parentElement.classList.remove("filled");
  });
}


.filled label,
input:focus   label,
textarea:focus   label {
  top: 0;
  font-size: 1.2rem;
}

These are HTML, Javascript and CSS codes in order. What I'm trying to achieve here is that once user writes email address/message, labels that are inside of input/textarea go up. So, when input/textarea are filled up, labels should disappear to the top. It does its job but not responsively. "filled" class is added after a couple of more clicks happen, which means that labels only go up to the top after I click the box again.

enter image description here

Result looks like this.

enter image description here

This is only achieved after a few more clicks in the box.

CodePudding user response:

You don't need js here at all. The :placeholder-shown pseudo-class will do what you actually need to achieve (note the non-empty placeholder attrs required for chrome):

.control {
  position: relative;
  margin-top: 20px;
}

input label,
textarea label {
  position: absolute;
  left: 0;
  top: 0;
  transition: 300ms;
}

input:focus label,
input:not(:placeholder-shown) label,
textarea:focus label,
textarea:not(:placeholder-shown) label {
  top: -20px;
}
<div >
  <input type="email" id="email"  placeholder=" " />
  <label for="email">Email</label>
</div>
<div >
  <textarea id="message" placeholder=" "></textarea>
  <label for="message">message</label>
</div>

Here's a codepen.

CodePudding user response:

In your css use: transform:translateY(-2em) change accordingly to your adjustment.

  • Related