Created
September 8, 2010 19:40
-
-
Save ralphholzmann/570700 to your computer and use it in GitHub Desktop.
This is what I use now
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function( $ ){ | |
$.fn.placeholder = function() { | |
var id = 0; | |
return this.data('placeholder') ? this : this.each(function(){ | |
// Create label | |
var $this = $(this) | |
, label = (function( props ) { | |
// Create label | |
var elem = $('<label />', { | |
'css' : { | |
'position' : 'absolute', | |
'color' : '#999999', | |
'cursor' : 'text', | |
'float' : 'none' | |
}, | |
'for' : (function( e ) { | |
if ( ! e.attr('id') ) { | |
e.attr('id', 'placeholder_' + ++id) | |
} | |
return e.attr('id'); | |
})( $this ), | |
'text' : $this.attr('placeholder') | |
}) | |
, display; | |
$this.removeAttr('placeholder'); | |
// Copy properties from the original input | |
$.each( props, function( i, v ){ | |
elem.css(v, $this.css(v)); | |
}); | |
// Hack because Firefox is bad at | |
// calculating line-height | |
if ($this.is('input')) { | |
elem.css('line-height', $this.css('height')); | |
} | |
// Make sure the parent is relatively positioned | |
display = $this.parent().css('position', 'relative').css('display'); | |
$this.parent().show(); | |
// CSS doesn't have the += operator, and I'm lazy | |
elem.animate( $.extend({ | |
'padding-left' : '+=' + $this.css('border-left-width'), | |
'padding-top' : '+=' + $this.css('border-top-width') | |
}, $this.position()), 0); | |
$this.parent().css('display', display); | |
// Return the newly created placeholder label | |
return elem; | |
})( 'font-size font-family font-weight padding-left padding-top margin-left margin-top width height line-height text-align'.split(' ')) | |
// Add to document | |
$this.before( label ); | |
// Show label if input is empty on blur | |
$this.bind('blur change keydown', function(){ | |
setTimeout(function(){ | |
if ( $this.val() ) { | |
label.hide(); | |
} else { | |
label.css('color', '#999999').show(); | |
} | |
}, 10); // Timeout fixes input masks | |
}).bind('focus', function(){ | |
label.css('color', '#cccccc'); | |
if($this.hasClass('hideOnFocus')){ | |
label.hide(); | |
} | |
}).blur(); | |
// Save reference to placeholder | |
$this.data('placeholder', label); | |
$(window).resize(function(){ | |
label.css( $this.position() ); | |
}); | |
}); | |
}; | |
})( jQuery ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Let's make this a repo?