Created
May 31, 2009 20:33
-
-
Save minaguib/121021 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
This JS class allows an easy and clean way to assign a "field hint" on input elements' values | |
usage: | |
new FieldHint("search_field", "Search..."); | |
It'll set the value of "search_field" to "Search..." whenever it's empty, | |
It'll erase the hint whenever the user focuses on that field, and restores back the hint if the user leaves the field without entering anything. | |
It'll also make sure on form submission to set it back to empty so there's nothing to do server-side. | |
It'll also add the field class "hint" to allow you to style it differently if needed. | |
Requires Prototype.js | |
Copyright (C) 2009 Mina Naguib. | |
Released under the GPL license. | |
*/ | |
var FieldHint = Class.create({ | |
initialize: function(field, hint) { | |
this.dom_field = $(field); | |
this.dom_form = $(this.dom_field.form); | |
this.hint = hint; | |
this.start_observing(); | |
this.possibly_set_hint(); | |
}, | |
start_observing: function() { | |
this.bound_field_focus = this.field_focus.bindAsEventListener(this); | |
this.dom_field.observe('focus', this.bound_field_focus); | |
this.bound_field_blur = this.field_blur.bindAsEventListener(this); | |
this.dom_field.observe('blur', this.bound_field_blur); | |
this.bound_form_submit = this.form_submit.bindAsEventListener(this); | |
this.dom_form.observe('submit', this.bound_form_submit); | |
}, | |
field_focus: function(e) { | |
this.possibly_erase_hint(); | |
}, | |
field_blur: function(e) { | |
this.possibly_set_hint(); | |
}, | |
form_submit: function(e) { | |
this.possibly_erase_hint(); | |
}, | |
possibly_erase_hint: function() { | |
var v = $F(this.dom_field); | |
if (v == this.hint) { | |
this.dom_field.value = ""; | |
this.dom_field.removeClassName("hint"); | |
} | |
}, | |
possibly_set_hint: function() { | |
var v = $F(this.dom_field); | |
if (v.match(/^\s*$/)) { | |
this.dom_field.value = this.hint; | |
this.dom_field.addClassName("hint"); | |
} | |
} | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Needless to say, 10 years later, just use
<input... placeholder="foo">
instead of the above