Input With Material Design Type Effect

Input with label moving above when you enter text

Below you can find an example that illustrates how to make a form with floating input labels. By default, the label covers the input field, and when you focus on it the label moves above and becomes smaller. This effect became popular as part of the Google Material Design specs.

How it was made

When you start entering text in the input field, you trigger a Javascript function checkEmpty() that checks if the input is empty or not and adds or removes the “has text” class. The floating label effect is done with CSS transition.

All fields below are editable. You can experiment with the code and see the result instantly:
<form>
<div class="card">
<div class="form-group">
<input class="input" type="text" id="user-first-name">
<label for="user-first-name">First Name</label>
</div>
<div class="form-group">
<input class="input" type="text" id="user-last-name">
<label for="user-last-name">Last Name</label>
</div>
</div>
</form>
HTML
* {
box-sizing:border-box;
margin: 0;
padding: 0;
}

@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed');

body {
background: #e2e2e2;
font-family: 'Roboto Condensed', sans-serif;
}

.card {
background: #fff;
border-radius: 2px;
display: block;
margin: 20px auto 0;
padding: 20px;
max-width: 300px;
width:100%;
text-align: left;
box-shadow: 0 1px 3px rgba(0,0,0,0.15), 0 1px 2px rgba(0,0,0,0.25);
}

.form-group {
position: relative;
margin: 10px 0 15px;
}

.form-group:last-child {
margin-bottom: 0;
}

.form-group label {
color: #666;
font-size: 15px;
position: absolute;
pointer-events: none;
top: 10px;
transition: 0.2s ease all;
width: 100%;
}

.input {
background-color: transparent;
color: #666;
font-size: 15px;
padding: 10px 10px 10px 0;
position: relative;
display: block;
border: none;
width: 100%;
border-bottom: 1px solid #ddd;
}

.input:focus {
outline: none;
}

.input:focus + label,
.input.has-text + label {
top: -10px;
font-size: 12px;
color: #2962ff;
}
CSS
(function($) {
var formInput = $(".input");

function checkEmpty(checkInput) {
if(checkInput.val()) {
checkInput.addClass("has-text");
} else {
checkInput.removeClass("has-text");
}
}

checkEmpty(formInput);

formInput.change(function(){
checkEmpty($(this));
});
})(jQuery);
JavaScript/jQuery 1.x
Plugins used:
jQuery Apache 2.0
Browser support:
           
9+