Captionator using JQuery

Posted by on Feb 27, 2011 in Code Chat | No Comments

A nice effect is to have the caption for a text field within the field instead of having a separate label.
However it can be frustrating for a user if they have to delete the text before they can type into it.

This JavaScript class looks for texfields with a class of captionate and adds the label as the default text which will clear when a user clicks it.

The benefits of this method are that it retains the proper markup by requiring field labels and it falls back gracefully by not hiding the label if the browser doesn’t support Javascript.




<script type="text/javascript">// <![CDATA[ captionator = { captions:Array(), init:function() { $.each($('input.captionate'), function() { id = $(this).attr('id'); label = $("label[for='"+id+"']"); if (label.length==0){ label = $(this).val(); } $(label).css('display', 'none'); captionator.captions[id] = label.text(); if ($(this).val()=='') { $(this).val(captionator.captions[id]); } $(this).click(function() { id = $(this).attr('id'); if ($(this).val()==captionator.captions[id]) { $(this).val(''); } }); $(this).blur(function() { id = $(this).attr('id'); if ($(this).val()=='') { $(this).val(captionator.captions[id]); } }); }); } } $(document).ready(function() { captionator.init(); }); // ]]></script>
<fieldset><label for="namefield">Your Name</label>
<input id="namefield" class="captionate" name="namefield" type="text" /></fieldset>

Leave a Reply