Simulation of a placeholder
With a small markup change and a script you can do this
The script simply append the user value to its value attribute, so one can use CSS to style it
p label {
position: relative;
}
p label input {
margin-top: 10px;
}
p label input[required] + span::after {
content: ' *';
color: red;
}
p label span {
position: absolute;
top: 2px;
left: 5px;
pointer-events: none;
transition: top .5s;
}
p label input:not([value=""]) + span,
p label input:focus + span {
top: -20px;
}
<p>
<label>
<input oninput="this.setAttribute('value', this.value)" type="text" name="your-name" value="" size="40" required>
<span>Name</span>
</label>
</p>
Since changing a HTML5 input's placeholder with CSS is a hot topic, here is a few more alternatives, with a simpler, more reusable markup structure
.placeholder {
position: relative; padding-top: 15px;
}
.placeholder label {
position: absolute; top: 17px; left: 5px;
pointer-events: none; transition: top .5s;
}
.placeholder input[required] + label::after {
content: ' *'; color: red;
}
.placeholder input:not([value=""]) + label,
.placeholder input:focus + label {
top: -5px;
}
<div class="placeholder">
<input oninput="this.setAttribute('value', this.value)" type="text" name="name" value="" required>
<label>Name</label>
</div>
Since the script is very small, I applied it inline, though one can of course add the same behavior with an external event handler, like this, and target more than one input
.
window.addEventListener('load', function() {
var placeholders = document.querySelectorAll('.placeholder input');
for (var i = 0; i < placeholders.length; i++) {
placeholders[i].addEventListener('input', function() {
this.setAttribute('value', this.value);
})
}
})
.placeholder {
position: relative; padding-top: 15px;
}
.placeholder + .placeholder {
margin-top: 10px;
}
.placeholder label {
position: absolute; top: 17px; left: 5px;
pointer-events: none; transition: top .5s;
}
.placeholder input[required] + label::after {
content: ' *'; color: red;
}
.placeholder input:not([value=""]) + label,
.placeholder input:focus + label {
top: -5px;
}
<div class="placeholder">
<input type="text" name="name" value="" required>
<label>Name</label>
</div>
<div class="placeholder">
<input type="text" name="email" value="" required>
<label>Email</label>
</div>
<div class="placeholder">
<input type="text" name="address" value="">
<label>Address</label>
</div>