Skip to content

Instantly share code, notes, and snippets.

@djfarrelly
Created July 10, 2014 23:08
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 djfarrelly/98701101d8a005128543 to your computer and use it in GitHub Desktop.
Save djfarrelly/98701101d8a005128543 to your computer and use it in GitHub Desktop.
jQuery placeholder polyfill using Modernizr
;(function($){
function inputFocus(){
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}
function inputBlur(){
var input = $(this);
if (input.val() === '' || input.val() === input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}
function removePlaceholderValue(){
var input = $(this);
if (input.val() === input.attr('placeholder')) {
input.val('');
}
}
function formSubmit(){
$(this).find('[placeholder]').each( removePlaceholderValue );
}
// Polyfill for placeholder attribute for older browsers
function placeholderPolyfill(element){
var placeholderSupported = !!( 'placeholder' in document.createElement('input') );
if (!placeholderSupported){
// If the input has the attribute 'nopolyfill' we skip it. Useful for login page
var selector = '[placeholder]:not([nopolyfill])',
placeholders = element instanceof $ ? element.find(selector) : $(selector),
forms = placeholders.parents('form');
placeholders
.on('focus', inputFocus)
.on('blur', inputBlur)
.trigger('blur');
forms.submit( formSubmit );
}
}
placeholderPolyfill();
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment