Skip to content

Instantly share code, notes, and snippets.

@davetayls
Created January 28, 2013 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davetayls/4654366 to your computer and use it in GitHub Desktop.
Save davetayls/4654366 to your computer and use it in GitHub Desktop.
jquery.hint using placeholder
/**
* @author Remy Sharp
* @url http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/
*/
/*jshint curly:false */
(function ($) {
var isInputSupported = 'placeholder' in document.createElement('input'),
isTextareaSupported = 'placeholder' in document.createElement('textarea');
// bail if this functionality is supported
if (isInputSupported && isTextareaSupported) return;
$.fn.hint = function (blurClass) {
if (!blurClass) {
blurClass = 'blur';
}
return this.each(function () {
// get jQuery version of 'this'
var $input = $(this),
// capture the rest of the variable to allow for reuse
title = $input.attr('placeholder'),
$form = $(this.form),
$win = $(window);
function remove() {
if ($input.val() === title && $input.hasClass(blurClass)) {
$input.val('').removeClass(blurClass);
}
}
// only apply logic if the element has the attribute
if (title) {
// on blur, set value to title attr if text is blank
$input.blur(function () {
if (this.value === '') {
$input.val(title).addClass(blurClass);
}
}).focus(remove).blur(); // now change all inputs to title
// clear the pre-defined text when form is submitted
$form.submit(remove);
$win.unload(remove); // handles Firefox's autocomplete
}
});
};
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment