Last active
December 15, 2015 23:09
-
-
Save jonkemp/5337793 to your computer and use it in GitHub Desktop.
Placeholder polyfill for inputs. Detects support for the placeholder attribute on inputs. If it is not present, the placeholder attribute text is inserted into the input, and a class of "placeholder-text" is added to the input. On keydown on the input, the placeholder text and the class is removed. On blur, if the input is empty, the 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
// Jonathan's placeholder polyfill | |
// *Requires jQuery | |
(function () { | |
function PlaceholderDefaults() { | |
return { | |
'placeholderText': '', | |
'className': '' | |
}; | |
} | |
function placeholderInit(selector, options) { | |
var obj = new PlaceholderDefaults(); | |
$.extend(obj, options); | |
if ($(selector).val() === '') { | |
$(selector).val(obj.placeholderText).addClass(obj.className); | |
} | |
} | |
function placeholderRemove(selector, options) { | |
var obj = new PlaceholderDefaults(); | |
$.extend(obj, options); | |
if ($(selector).val() === obj.placeholderText) { | |
$(selector).val('').removeClass(obj.className); | |
} | |
} | |
if ('placeholder' in document.createElement('input') === false) { | |
$('input[placeholder]').each(function () { | |
var options = new PlaceholderDefaults(); | |
options.placeholderText = $(this).attr('placeholder'); | |
options.className = 'placeholder-text'; | |
$(this).on('focus', function () { | |
placeholderRemove(this, options); | |
}); | |
$(this).on('blur', function () { | |
placeholderInit(this, options); | |
}); | |
placeholderInit(this, options); | |
}); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment