Submit your widget

Useful jQuery Form Add Hints and Auto Focus effect

Created 9 years ago   Views 17051   downloads 3363    Author ajaxblender
Useful jQuery  Form  Add Hints and Auto Focus effect
View DemoDownload 25.8 KB
Share |

This demo teaches you how to easily add hints to your forms and auto focus fields.

We are continuing a series of quick articles for web developers which explain how to automate things during website programming. Today we will talk about forms and two usability items the every current website should have:

  • Auto Focus Fields. The first field in the form should be focused by default, so that the user can start entering his password or name right after page loaded and would not have to click the field to start typing. This is a small and obvious usability items, but still a very important one.
  • Hints. Forms should have quick tips for fields which requires entering data in a specific format (for example email address, phone number, date / time, etc.)

Auto Focus

Full Name – this field will be automatically focused when the page loads, here is how it will be coded in the markup:

<input type="text" name="fullname" id="fullname" class="auto-focus" />

Notice the field has ‘auto-focus’ class. This is so that any field in the form with this CSS class will be automatically focused on page load.

The auto focus can be implemented in JavaScript:


2.) Email Address (the same for phone number and message fields) – If the field does not contain any value it will show a quick tip on the required data format. When the user clicks the field, the tip will disappear and let the user enter data. Here is how it will look in the markup:

<input type="text" name="email" id="email" title="i.e." class="auto-hint" />

As you see, our hint will be stored in ‘title’ attribute of the field. This will let user see it when the field already contains a value in it.

By default, the color of text in input field will be black, we need to differentiate the color of the hint and common input value. Let’s set this color in CSS:

<style type="text/css">
    .auto-hint { color: #AAAAAA; }

Now we move to JavaScript implementation. At first we should display the hint in fields which have empty values:

    if($(this).val() == $(this).attr('title')){

And handle focus / blur events:

    if($(this).val() == '' &amp;&amp; $(this).attr('title') != ''){
    if($(this).attr('title') == ''){ return; }
    if($(this).val() == ''){ $(this).val($(this).attr('title')); }
    else { $(this).removeClass('auto-hint'); }

That’s it! ;)The article source: