Question

I want to be able to do something like

<input type="text" name="txtField" value="" title="input your text" />
<textarea name="areaField" title="input your long text"></textarea>

And the title will auto fade out and back in as the field value, unlike the "search" here in stackoverflow (right on the top, it only fade out).

I could come up with a javascript and use onblur and onfocus, but that would be troublesome and I hope unnecessary. Preferably, I'd set just a single function for every INPUT and TEXTAREA within any given file, so all I need to do is set up its title.

First question: what's the name for this?

Main question: Anyone have a good solution? What about with no jquery? Maybe there's a way to do it with CSS3 only, though I doubt it...

Was it helpful?

Solution

If you're OK with it only working in newer browsers, you could use the placeholder attribute on the text field, to supply a placeholder that will disappear when you focus and reappear when you blur. You can find some more info in Dive Into HTML5.

<input type="text" name="txtField" value="" placeholder="input your text" />

If you want it to work in older browsers, you'll probably have to implement the placeholder yourself, in JavaScript for instance. You can find all of your input and textarea elements using document.getElementsByTagName and add the onfocus and onblur handlers to each of those using DOM events.

OTHER TIPS

Ok, thanks to Brian's perfect answer, this is the code I came up with. Took me long enough to make it work:

<form>
  <input type="text" name="txtField" value="" placeholder="input your text" />
  <textarea name="areaField" placeholder="input your long text"></textarea>
</form>

<script type="text/javascript">
(function() {
    ie_placeholder(document.getElementsByTagName('input'));
    ie_placeholder(document.getElementsByTagName('textarea'));
    function ie_placeholder (fields) {
        for (var i = 0; i < fields.length; i++) {
            var field = fields[i];
            field.onfocus = function () {
                if (this.value == this.placeholder) {
                    this.style.color = '';
                    this.value = '';
                }
            };
            field.onblur = function () {
                if (this.value == '' && this.placeholder != null) {
                    this.style.color = 'silver';
                    this.value = this.placeholder;
                }
            };
            field.onblur();
        }
    }
})();
</script>

Just put it in the end of the form, and you should be fine. And, please, use your favorite server side script to remove this from HTML5 compatible browsers. The placeholder attribute will just work on HTML5.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top