Created
May 20, 2013 21:11
-
-
Save mcrumley/5615608 to your computer and use it in GitHub Desktop.
HTML 5 placeholder support for older browsers.
This file contains hidden or 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($) { | |
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.Custom class name
The
placeholder()
function can also be used to change the class name set when the placeholder is visible.The default class name is "placeholder".