moraga – 6:43 pm

Placeholder plugin for jQuery

html5

Placeholder its a new attribute of HTML5. Your functionality is add label inside inputs when empty.

>input type="text" placeholder="Enter your name here!" />

Some browsers like Firefox in version 3.6 doesn’t have support for this attribute.

The code below is an plugin for jQuery that simulate placeholder.

(function($) {
	$.fn.extend({
		placeholder: function() {
			return this.each(function() {
				$('[placeholder]', this)
					.focus(function() {
						if ($(this).val() == $(this).attr('placeholder'))
							$(this).val('').css('color', '#000');
					})
					.blur(function() {
						if (!$(this).val() || $(this).val() == $(this).attr('placeholder'))
							$(this).val(function() { return $(this).attr('placeholder') }).css('color', '#ccc');
					})
					.filter(':not([value])').val(function() { return $(this).attr('placeholder') }).css('color', '#ccc')
					.parents('form')
						.bind('submit', function() {
							$('[placeholder]', this).val(function() { return $(this).val() != $(this).attr('placeholder') ? $(this).val() : '' });
						});
			});
		}
	});
})(jQuery);

To use is very simple. Put the attribute into HTML tags normally and in the parent of all elements that you use execute the code:

$('parent').placehoder();

Example:

$('form').placeholder();