I have a form in which when input
is clicked the label goes through a transition. If a value is entered in the input field, the label stays there. But the transition for when a value is entered is not working for textarea
.
Input labels
are behaving correctly but not the textrea label
My HTML for form:
if($.trim($("textarea").val()) != '') {
$("textarea").css("border: 2px solid blue");
}
.input-field {
position: relative;
margin-bottom: 18px;
}
.input-field input,
.input-field textarea {
width: 100%;
height: 40px;
font-size: 18px;
padding: 0 15px;
border: 1px solid grey;
background: transparent;
color: black;
outline: none;
}
.input-field label {
position: absolute;
top: 50%;
left: 15px;
transform: translateY(-50%);
color: grey;
font-size: 19px;
pointer-events: none;
transition: 0.3s;
}
input:focus,
textarea:focus {
border: 1px solid black;
}
input:focus~label,
input:valid~label,
textarea:focus~label,
{
top: -5px;
left: 15px;
font-size: 16px;
padding: 0 2px;
background: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="input-field">
<input type="text" required spellcheck="false">
<label>Name</label>
</div>
<div class="input-field">
<input type="text" required spellcheck="false">
<label>Email</label>
</div>
<div class="input-field">
<textarea style="min-height: 45px "> </textarea>
<label>Your Message</label>
</div>
I tried using jQuery css()
to target the the textarea border on textarea input just to see if I can do the same for its label
, but its not working.
I want the label for textarea to behave as ther labels for input are.
2
Answers
You might not need JavaScript (jQuery).
<label>
semantically and properly. Wrap textarea and input into Label, or use thefor=""
attribute. I’ll use the simpler wrapping method, and therefore put the actual label text into a SPAN Element.placeholder=" "
and in CSS:not(:placeholder-shown)+span {
to target the label SPAN when input or textarea has value (placeholder is not shown)Why not just use the build-in functionality of the attribute placeholder. I know it is not doing a transition or anything, but it works and there is less code to maintain.