views:

65

answers:

4

This is a very common usecase we see on stackoverflow, facebook, etc.

You often want to give the user some text to direct him on what to do, but you want the text to disappear the moment he clicks on it.

What is the easiest way to do that via JQuery? This seems like a fairly common use case

+2  A: 

I use this simple script on my search input:

$(document).ready(function () {

    searchInput = $('#search-input');
    searchDefault = 'Please enter text';

    searchInput.click(function () {
        if($(this).val() == searchDefault)
            $(this).val('');
    });

    searchInput.blur(function () {
        if($(this).val() == '')
            $(this).val(searchDefault);
    });

});

You could also assign some other functions like changing the color or some effects to the click and blur events.

Viktor Stískala
thanks a lot victor! i think i am going to go w the plugin as described above first, will go with this if that is too complex =)
ming yeow
+3  A: 

What I think you're looking for is generally called a "watermark" - and you're right, this is very common. There are a number of jQuery plugins available to do just what you're asking.

For example: http://code.google.com/p/jquery-watermark/

Eric
thanks for sharing the term "watermark" - much appreciated!
ming yeow
+2  A: 

Here we go - snippet on jsfiddler.net

jQuery:

$(function() {
    $('#placeholderText').val("Placeholder")
        .focusin(function(){
            if($(this).hasClass('initialClass'))
                $(this).removeClass('initialClass').
                    addClass('normalClass').val('');                
        })
        .focusout(function(){
            if($(this).hasClass('normalClass') && $(this).val() == '')
                $(this).removeClass('normalClass').
                    addClass('initialClass').val('Placeholder');    
        });
});

CSS:

.initialClass {
    color: #999999;
}

.normalClass {
    color: #000000;
}

HTML:

Click on me: <input id="placeholderText" type="text" class="initialClass" />
Floyd Pink
+1  A: 

If the instruction text is inside the textarea you can use the toggleVal plugin. I have not used the jquery watermark plugin, it could be better so take a look at both. http://jquery.kuzemchak.net/toggleval.php

HTML:

<label for="field1">Some text to explain the text area.</label>
<textarea id="field1" name="textarea1"></textarea>

CSS:

.toggleval {
  font-style: italic;
  color:#333;
}
.tv-changed, .tv-focused {
  font-style: normal;
  color:#000;
}

Javascript:
$('.toggle').toggleVal({
    populateFrom: "label",
    removeLabels: true
});
Keyo
Thanks Keyo! I will evaluate both watermark and toggleval. ;)
ming yeow