Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Form label animation with no-js fallback

Form label animation with no-js fallback

Simply add a surrounding element with a class name of "input-wrap" then add a class to your input, textarea etc... of "input-wrap__field" and you should see some sweet animation :)

A Pen by Matthew Neil on CodePen.

License.

<div class="center-form">
<form class="form">
<fieldset>
<legend>Awesome label transition</legend>
<ul>
<li class="input-wrap">
<label for="txtName">Name</label>
<input type="text" id="txtName" class="input-wrap__field" />
</li>
<li class="input-wrap">
<label for="txtEmail">Email</label>
<input type="email" id="txtEmail" class="input-wrap__field" />
</li>
<li class="input-wrap">
<label for="txtArea">Comments</label>
<textarea id="txtArea" class="input-wrap__field"></textarea>
</li>
</ul>
</fieldset>
</form>
</div>
// add class to html
document.querySelector('html').classList.add('js');
// smart wrapper querySelectorAll
var elSelect = function ( elem ) {
return document.querySelectorAll( elem );
}
// smart wrapper for each
function forEachItem(selector, fn){
var elements = elSelect(selector);
for (var i = 0; i < elements.length; i++){
fn(elements[i], i);
}
}
forEachItem('.input-wrap', function(element, i){
var inputItem = element.querySelector('.input-wrap__field');
var labelItem = element.getElementsByTagName('label');
element.appendChild(labelItem[0], inputItem[1]);
if (inputItem){
inputItem.addEventListener('blur', function(){
if (inputItem.value !== ''){
inputItem.classList.add('valid');
} else {
inputItem.classList.remove('valid');
}
});
}
});
// Notes
// #1 will only work in IE8>
@border:#c2c2c2;
// mixins
.input-style(@radius:5px, @pad:12px, @border-color:#c2c2c2){
border-radius:@radius; // #1
background-color:transparent;
padding:@pad;
border:1px solid @border-color;
}
// This is just to center the form
.center-form {
margin:20px auto;
width:25%;
}
.form {
ul {
margin:0;
padding:0;
}
li {
list-style-type:none;
margin:40px 0;
}
label{
display:block;
margin:0 0 10px 5px;
}
}
// if js enabled a class is added to html
.js {
.input-wrap {
position:relative;
label {
color:#c2c2c2;
position:absolute;
top:0.8em;
transition:all 0.25s cubic-bezier(0.175, 0.885, 0.32, 1.275);
transform:translate3d(0, 0, 0);
z-index:-1;
}
input, textarea {
&:focus, &.valid {
~ label {
color:#000;
transform:translate3d(0, -2.2em, 0);
}
}
}
}
}
input {
&[type="email"],
&[type="text"]
{
box-sizing:border-box; // #1
width:100%;
.input-style();
}
}
textarea {
box-sizing:border-box; // #1
width:100%;
min-height:100px;
resize:none;
.input-style();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment