Louis' Blog

All about software development for the web

Animated CSS Label

A simple example of an input field with placeholder text which moves out of the way when text is entered:



How it’s done

HTML

1
2
3
4
<form>
<input name="myInput" id="myInput" class="animated-input" type="text">
<label for="myInput">Placeholder</label>
</form>

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
input[type="text"] {
box-sizing: border-box;
height: calc(2em + 1px);
padding: 0.5em;
border: 1px solid #999;
background: #fff;
resize: none;
outline: none;
display: block;
line-height: 1em;
}
input[type="text"]:focus {
border-color: #00bafa;
}
input[type="text"]:focus + label {
color: #00bafa;
}
input[type="text"]:focus + label,
input[type="text"].filled-in + label {
transition-duration: .2s;
transform: translate(0, -3em) scale(0.9, 0.9);
background-color: #fff;
}
input[type="text"] + label {
display: inline-block;
margin: 0 calc(1em + 2px);
padding: 0 2px;
color: #999;
white-space: nowrap;
transition: 0.3s ease;
transform: translate(0, -1.6em)
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// Add listener for when input is blurred
var matches = document.querySelectorAll('.animated-input');
for (var i=0; i<matches.length; i++){
addEvent(matches[i],'blur',onAnimatedInputBlur);
}
// when input is blurred, check if the value is empty
function onAnimatedInputBlur(event){
if(event.target.value){
//if input is non-empty, keep placeholder out of the way
addClass(event.target,'filled-in');
}else{
removeClass(event.target,'filled-in');
}
}
// helper functions
function hasClass(el, className) {
return el.classList ? el.classList.contains(className) : new RegExp('\\b'+ className+'\\b').test(el.className);
}
function addClass(el, className) {
if (el.classList) el.classList.add(className);
else if (!hasClass(el, className)) el.className += ' ' + className;
}
function removeClass(el, className) {
if (el.classList) el.classList.remove(className);
else el.className = el.className.replace(new RegExp('\\b'+ className+'\\b', 'g'), '');
}
function addEvent(el, type, handler) {
if (el.attachEvent) el.attachEvent('on'+type, handler); else el.addEventListener(type, handler);
}