Skip to content

Instantly share code, notes, and snippets.

@mcrumley
Created May 20, 2013 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mcrumley/5615608 to your computer and use it in GitHub Desktop.
Save mcrumley/5615608 to your computer and use it in GitHub Desktop.
HTML 5 placeholder support for older browsers.
(function($) {
var defaults = {
className: "placeholder"
};
if ("placeholder" in document.createElement("input")) {
$.fn.placeholder = function(){ return this; };
} else {
$.fn.placeholder = function(options){
options = $.extend({}, defaults, options);
options.className += " --placeholder-active";
this.removeClass(options.className);
this.each(function() {
var input = $(this);
var placeholder = input.attr("placeholder");
var form = $(this.form);
if (placeholder) {
if (input.val() === "") {
input.val(placeholder);
input.addClass(options.className);
}
if (!form.data("placeholderInitComplete")) {
form.submit(function() {
form.find("input, textarea").each(function() {
var input = $(this);
if (input.hasClass("--placeholder-active")) {
input.val("");
input.removeClass(options.className);
}
});
});
form.data("placeholderInitComplete", true);
}
input.off("focus.placeholder").on("focus.placeholder", function() {
if (input.hasClass("--placeholder-active")) {
input.removeClass(options.className);
input.val("");
}
});
input.off("blur.placeholder").on("blur.placeholder", function() {
if (input.val() === "") {
input.val(placeholder);
input.addClass(options.className);
}
});
input.off("change.placeholder").on("change.placeholder", function() {
if (input.val() !== "") {
input.removeClass(options.className);
}
});
}
});
return this;
};
$(document).ready(function() {
$("input, textarea").placeholder();
});
}
})(jQuery);
@mcrumley
Copy link
Author

Initialization

<input> and <textarea> elements with placeholder attributes are automatically configured during the jQuery ready event. If you create additional form elements later, you can initialize them manually.

$("selector").placeholder();

Custom class name

The placeholder() function can also be used to change the class name set when the placeholder is visible.

$("selector").placeholder({className: "custom"});

The default class name is "placeholder".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment