Skip to content

Instantly share code, notes, and snippets.

@aron
Created January 5, 2010 09:52
Show Gist options
  • Save aron/269284 to your computer and use it in GitHub Desktop.
Save aron/269284 to your computer and use it in GitHub Desktop.
Function to clear placeholder text in an input element.
/**
* Function to clear placeholder text in an input element.
*
* Clears the input on focus unless the user has already
* entered data, if the input is blank on blur the placeholder
* will be reinserted.
*
* Uses the value supplied in the _placeholder_ attribute on
* the input element. If this is not present it will default
* to the _value_ attribute.
*
* NOTE: Implementation will default to the native browser
* implementation if supported.
*/
function clearPlaceholder (field) {
var placeholder = field.getAttribute('placeholder') || field.value;
if (clearPlaceholder.supported === undefined) {
clearPlaceholder.supported = ('placeholder' in document.createElement('input'));
}
if ( ! clearPlaceholder.supported) {
field.value = field.value || placeholder;
field.onfocus = function () {
if (this.value === placeholder) {
this.value = '';
}
};
field.onblur = function () {
if (this.value === '') {
this.value = placeholder;
}
};
}
}
// Call when document has loaded.
// Example Input Element: <input type="email" name="email" placeholder="hello@example.com" value="" />
var input = document.getElementById('signup').getElementsByTagName('input')[0];
clearPlaceholder(input);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment