Skip to content

Instantly share code, notes, and snippets.

@theophani
Created January 10, 2011 10:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theophani/772628 to your computer and use it in GitHub Desktop.
Save theophani/772628 to your computer and use it in GitHub Desktop.
shows and hides a label, used as placeholder text
// Relevant HTML and JS
<label for="searchbox" id="searchboxPlaceholder">Search</label>
<input type="text" name="Query" id="searchbox" />
<script>
(function(d){
var sb = d.getElementById('searchbox'),
ph = d.getElementById('searchboxPlaceholder');
var hide = function() {
ph.style.display = 'none';
};
var show = function() {
if (sb.value === '') {
ph.style.display = 'block';
}
};
if (sb.value !== '') { // is field is prefilled on page load?
hide();
}
if (sb.addEventListener) {
sb.addEventListener('focus', hide, false);
sb.addEventListener('blur', show, false);
} else if (sb.attachEvent) {
sb.attachEvent('onfocus', hide);
sb.attachEvent('onblur', show);
}
}(document));
</script>
// Relevant CSS
//
// Note that my form has "position: relative",
// and the input field #searchbox has some padding and things
// that I have adjusted for, hence the "top: 9px; left: 5px;" below
#searchboxPlaceholder { position: absolute; top: 9px; left: 5px; font-size: 12px; color: #e8e8e8; }
@theophani
Copy link
Author

I added this:
if (sb.value !== '') { // is field is prefilled on page load?
hide();
}
which is a fix for when the field is prefilled, either from the server, or when the user uses the back button

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment