Created
March 1, 2012 09:38
-
-
Save lucaong/1948570 to your computer and use it in GitHub Desktop.
jQuery plugin providing feature detection and cross-browser fallback for html5 input placeholder
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
/* Placeholders plugin for jQuery | |
* Use this to provide a graceful fallback for browsers not supporting the html5 placeholder attribute | |
* | |
* Usage: | |
* jQuery('form').placeholders(); // if the user's browser do not support placeholder, it implements a fallback | |
* | |
* You can also specify some options: | |
* jQuery('form').placeholders({ | |
* placeholderAttr: "title", // specify the attribute to get placeholder value from (default: 'placeholder') | |
* placeholderedClass: "custom-class" // the class added to the input element when its value is a placeholder (default 'placeholdered') | |
* }); | |
* | |
* Luca Ongaro | |
*/ | |
(function($) { | |
$.fn.placeholders = function(opts) { | |
var defaultOpts = { | |
placeholderedClass: "placeholdered", | |
placeholderAttr: "placeholder" | |
}, | |
hasPlaceholderSupport = function() { | |
var input = document.createElement('input'); | |
return ('placeholder' in input); | |
}, | |
setPlaceholder = function(elem) { | |
elem.val(elem.attr(opts.placeholderAttr)); | |
elem.addClass(opts.placeholderedClass); | |
}, | |
clearPlaceholder = function(elem) { | |
if (elem.val() == elem.attr(opts.placeholderAttr)) { | |
elem.val(""); | |
} | |
elem.removeClass(opts.placeholderedClass); | |
}; | |
opts = $.extend(defaultOpts, opts); | |
// Check placeholder support | |
if (!hasPlaceholderSupport() || opts.placeholderAttr != "placeholder") { | |
this.find("input["+opts.placeholderAttr+"]").each(function() { | |
var $input = $(this); | |
// Set value to placeholder when empty | |
if ($input.val() == '') { | |
setPlaceholder($input); | |
} | |
// Clear placeholder when focus | |
$input.on("focus change", function() { | |
if($input.hasClass(opts.placeholderedClass)) { | |
clearPlaceholder($input); | |
} | |
}).blur(function() { | |
if(!$input.hasClass(opts.placeholderedClass) && $input.val() == "") { | |
setPlaceholder($input); | |
} | |
}); | |
// Clear placeholder on submit | |
$input.closest("form").submit(function() { | |
if($input.hasClass(opts.placeholderedClass)) { | |
clearPlaceholder($input); | |
} | |
}); | |
}); | |
} | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment