Do you know how to perform the following functionality in Bootstrap or jQuery/JavaScript?
- Default input state with placeholder text (i.e. “Email” placeholder)
- Click that input
- Start typing your email address
- The “Email” placeholder disappears
- An “Email” label appears and moves up above the typed email address and inside of the input
You can view a demo of this on Shopify:
- Go to https://simpletheme.myshopify.com/collections/all/products/contrast-jacket?variant=335385313
- Add to Cart
- View Cart
- Check Out
- Enter an email address in the “Email” input
Here’s a starting point on Plunker:
https://plnkr.co/edit/bd9yGmgKfK53Tpn8rCSp?p=preview
<!DOCTYPE html>
<html>
<head>
<style>
label {
display: none;
}
</style>
</head>
<body>
<label>Email</label>
<br />
<input placeholder="Email" />
</body>
</html>
Any advice on how to replicate this functionality is greatly appreciated.
2
Answers
To replicate this functionality, you could use a
label
and a wrapper element (div
). Give thediv
relative position and to the label an absolute position and align it so that it sits on top of theinput
.Then you can hook up jQuery (or vanilla JS will also do fine) and listen for the
focus
and theblur
events. When the input is focused, you can add the label another class, which moves it further up and onblur
you should check the contents of theinput
viaevent.target.value
, to see if it’s empty and if so, remove the class from the label which made it move up.Hope that points you in the right direction.
A few key points to consider, however:
Unfortunately, CSS only will not be able to do the trick as you cannot target inputs depending on their actual value. (Read more here Detect if an input has text in it using CSS — on a page I am visiting and do not control?)
So the trick, taken from above post, is to listen on the inputs’ events and add a class to mark when the input has value. You’d have to run that function once the page loads if you happen to show some inputs with pre-filled input.
The remainder of the trick is about placing the label above the input and making sure the input has enough padding so the two texts do not overlap. I’ll let you the merit of styling it according to your needs.