Sticky Placeholders jQuery Plugin
HTML
<form>
<input type="text" id="name" size="30" placeholder="Name" />
<input type="text" id="email" size="30" placeholder="Email" />
<input type="password" id="password" size="30" placeholder="Password" />
<textarea id="text" cols="50" rows="5" placeholder="Random Text Goes Here..."></textarea>
</form>
CSS
body {
background-color:#EEE;
}
input, textarea {
margin:20px 100% 0 20px;
position:relative;
}
input,
textarea {
border:1px solid #808080;
box-shadow:0 0 2px rgba(0,0,0,.2) inset, 0 0 0 rgba(255,255,255,0);
outline:none;
-webkit-transition: all .2s ease-out;
-moz-transition: all .2s ease-out;
-ms-transition: all .2s ease-out;
transition: all .2s ease-out;
}
input:focus,
textarea:focus {
border:1px solid #00AEDB;
box-shadow:0 0 2px rgba(0,0,0,.2) inset, 0 0 5px rgba(0, 174, 219, .3);
}
input,
textarea {
font: 1em/1.3 Verdana, sans-serif;
padding:6px 8px;
}
.sticky-placeholder-wrapper > label {
opacity:.5; /* to prevent initial dimming in FF, set to the same value as placeholderOpacity (default: .5) */
-webkit-transition: opacity .2s ease-out;
-moz-transition: opacity .2s ease-out;
-ms-transition: opacity .2s ease-out;
transition: opacity .2s ease-out;
}
JavaScript
// Stick Placeholders jQuery Plugin
(function($) {
var alterParent = function(options, event) {
var label = $(this).data('label');
if (event && event.type === 'focusin') {
label.css('opacity', options.placeholderFocusOpacity);
} else if (event && event.type === 'focusout') {
label.css('opacity', options.placeholderOpacity);
}
if (event && event.type !== 'keydown') {
toggleLabel(this, label);
} else {
// Use timeout to catch val() just after the key is pressed
// Using keyup is too slow.
(function(input) {
setTimeout(function() {
toggleLabel(input, label);
}, 0);
})(this);
}
};
var toggleLabel = function(input, label) {
if ($(input).val()) {
label.hide();
} else {
label.show();
}
};
$.fn.stickyPlaceholders = function(options) {
var defaults = {
wrapperClass: 'sticky-placeholder-wrapper',
wrapperDisplay: 'block',
labelClass: 'sticky-placeholder-label',
placeholderAttr: 'placeholder',
dataAttr: 'data-sticky-placeholder',
placeholderColor: '#000',
placeholderOpacity: 0.5,
placeholderFocusOpacity: 0.25
};
options = $.extend(defaults, options);
return this.each(function() {
var input = $(this),
placeholder = input.attr(options.placeholderAttr),
wrapper = $(this).wrap('<span class="' + options.wrapperClass + '" />').parent().css({'position':'relative', 'display':options.wrapperDisplay}),
label = $('<label class="' + options.labelClass + '" for="' + input.attr('id') + '">' + placeholder + '</label>').appendTo(wrapper),
labelStyle;
// store a reference to each input's label
input.data('label', label);
// remove the placeholder attribute to avoid conflcits
input.removeAttr('placeholder');
// If the dataAttr is set and it's not equal to the placeholderAttr
if (...