Archive for March, 2010

Hint text for the input fields with jQuery

Wednesday, March 3rd, 2010

There are lot of site out of the Internet where some help text placed into the input fields. The working mechanism of this fields is easy. When the visitor clicks in the field the text disappear while he clicks somewhere else or navigate anywhere else on the site the text will appear again. This technique is very useful for your visitors to help them which kind of content do you waiting for that input field. It is a part of the user experience what your site can be gives for your visitors.

Needless to say that it is very easy to implement with some line of jQuery code! I would like to share it with this little snippets what I’m using my projects.

Let’s do some jQuery magic! :)


$.fn.hint = function(blurClass) {
              return this.focus(function() {
                if( this.value == this.title ) {
                  $(this).val("").removeClass(blurClass);
                }
              }).blur(function() {
                if( !this.value.length ) {
                  $(this).val(this.title).addClass(blurClass);
                }
              }).blur();
            };

To make it work on thedesired input fields just use it in this way:


$("#input_field_id").hint("help");

You can use any of the jQuery selector technique of course!

The parameter for the hint will be the style for displaying the hint text in the field. In this example I will make the text light grey – you can add it to your .CSS file or definitions:


.help {color:#999;}

OK. But you can ask me where is the hint text itself? It is in the input field title property! Here is one example what you can use your HTML:


<input type="text" value="" id="input_field_id" title="Here is a little help" />

That’s all! If you have any question just ask me.