Created
January 5, 2010 09:52
-
-
Save aron/269284 to your computer and use it in GitHub Desktop.
Function to clear placeholder text in an input element.
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
/** | |
* 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="[email protected]" 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