Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Have text that clears when you click on it

I would like to know how to implement something like stack overflow when you post a question: "At least one tag such as (css html asp.net), max 5 tags.

How can I implement something like this for a text input in html, where it is partially faded, but when you type, it doesn't show up, and is not faded.

I don't mind how to do this, as long as it works.

Thanks.

like image 495
H Bellamy Avatar asked Nov 12 '11 17:11

H Bellamy


2 Answers

The easiest option is to use the placeholder attribute:

<input type="text" placeholder="At least one tag, such as 'html', 'asp.net', max five tags." />

JS Fiddle demo.

If cross-compatibility is a requirement, then JavaScript is also an option:

var inputs = document.getElementsByTagName('input');

for (i=0; i<inputs.length; i++){
    if (inputs[i].hasAttribute('data-hint')){
        inputs[i].value = inputs[i].getAttribute('data-hint');
            inputs[i].style.color = '#999';

        inputs[i].onclick = function(){
            this.value = '';
        };
        inputs[i].onblur = function(){
            if (this.value == '' || this.value == this.getAttribute('data-hint')){
                this.value = this.getAttribute('data-hint');
                this.style.color = '#000';
            }
        };
    }
}

JS Fiddle demo.

Or, with jQuery:

$('input:text').each(
    function(){
        $(this).val($(this).attr('data-hint'));
            $(this).css('color','#999');
    }).click(
    function(){
        $(this).val('');
            $(this).css('color','#000');
    }).blur(
    function(){
        if ($(this).val() == ''){
            $(this).val($(this).attr('data-hint'));
            $(this).css('color','#999');
        }
    });

JS Fiddle demo.

References:

  • Common Input Element Attributes (W3.org).

Vanilla JavaScript:

  • document.getElementsByTagName().
  • element.onblur.
  • element.onfocus.
  • element.hasAttribute().
  • element.getAttribute().
  • element.style.

jQuery:

  • text-input (:text) selector.
  • .each().
  • .val().
  • .css().
  • .attr().
like image 197
David Thomas Avatar answered Sep 20 '22 14:09

David Thomas


<input type="text" name="booga" placeholder="This is default text" />
like image 24
Ilia G Avatar answered Sep 17 '22 14:09

Ilia G