I have a couple of <input> elements that I need to have HTML5-like placeholders for. The kind that disappear on focus and reappear on blur only if the input has no text. I’ve seen a few javascript-heavy implementations and I’ve been looking for a lightweight (preferably css-only) solution.
Here’s the HTML:
<div class="email-container">
<span class="default-value">Email</span>
<input class="text-input" name="login" type="email"/>
</div>
<div class="pw-container">
<span class="default-value">Password</span>
<input class="text-input" name="login" type="pw"/>
</div>
I couldn’t find anything that fit my bill perfectly (as in ‘css-only’), but I did come up with a couple of good solutions using jQuery:
I set the background of the input to transparent and the z-index of the ‘placeholder’ text to -1. This allows me to click ‘on’ the text and actually click the input. See this jsFiddle.
I allow the ‘placeholder’ text to sit over the input but I use a click handler on the text to transfer the focus to the input. See this jsFiddle.
In both instances, the workhorse of the implementation is this jQuery code:
The other important piece to the puzzle was figuring out how to use
position: absoluteandposition: relativeto make the ‘placeholder’ text sit nicely inside the input while still allowing the input to move freely.