Label Animation
by andrey90vs
HTML
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<div class="custom-input">
<label for="firstname">First Name</label>
<input type="text" class="form-control" id="firstname">
</div>
<div class="custom-input">
<label for="test">Test 1</label>
<input type="text" class="form-control" id="test">
</div>
<div class="custom-input">
<label for="test2">Test 2</label>
<input type="text" class="form-control" id="test2" placeholder="test 2">
</div>
<div class="custom-input">
<label>Test 3</label>
<input type="text" class="form-control" placeholder="Placeholder 3">
</div>
<div class="custom-input">
<label>Test 4</label>
<input type="text" class="form-control">
</div>
<div class="custom-input">
<input type="text" class="form-control" placeholder="Test 5">
</div>
SCSS
html {
padding: 100px;
}
.custom-input {
position: relative;
padding-top: 20px;
margin-bottom: 10px;
input {
padding-left: 15px;
}
label {
cursor: text;
margin: 0;
padding: 0;
left: 15px;
top: 27px;
position: absolute;
font-size: 14px;
color: #ccc;
font-weight: normal;
transition: all .3s ease;
&.active {
top: 0;
left: 0;
font-size: 12px;
&.focusIn {
color: #66afe9;
}
}
}
}
JavaScript
'use strict';
(function($) {
$.fn.phAnim = function( options ) {
// Set default option
var settings = $.extend({}, options),
label,
ph;
// get label elem
function getLabel(input) {
return $(input).parent().find('label');
}
// generate an id
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
return this.each( function() {
// check if the input has id or create one
if( $(this).attr('id') == undefined ) {
$(this).attr('id', makeid());
}
// check if elem has label or create one
if( getLabel($(this)).length == 0 ) {
// check if elem has placeholder
if( $(this).attr('placeholder') != undefined ) {
ph = $(this).attr('placeholder');
$(this).attr('placeholder', '');
// create a label with placeholder text
$(this).parent().prepend('<label for='+ $(this).attr('id') +'>'+ ph +'</label>');
}
} else {
// if elem has label remove placeholder
$(this).attr('placeholder', '');
// check label for attr or set it
if(getLabel($(this)).attr('for') == undefined ) {
getLabel($(this)).attr('for', $(this).attr('id'));
}
}
$(this).on('focus', function() {
label = getLabel($(this));
label.addClass('active focusIn');
}).on('focusout', function() {
if( $(this).val() == '' ) {
label.removeClass('active');
}
label.removeClass('focusIn');
});
});
};
}(jQuery));
$(document).ready(function() {
$('.custom-input input').phAnim();
});