HTML5 Placeholder

The new HTML5 attribute placeholder for the input tag could be wonderful if implemented correctly. Unfortunately, at the moment we have a problem on Firefox. When using placeholder on firefox, when focusing on the input field, the placeholder does not vanish. This gives the user the erroneous feel that the text is really there and attempts to “erase” it doesn’t work … it is in the background. The appearance is a bit confusing.

The following code can be used to create the “placeholder” behavior. Place a default value in an attribute called data-default, and that value will act as the placeholder.



    <script type="text/javascript">
      $(function() {
        $('input[type="text"]').focus(function() {
            if (!$(this).attr('data-default')) $(this).attr('data-default', $(this).val());
            if ($(this).val()==$(this).attr('data-default')) $(this).val('');
        });
        $('input[type="text"]').blur(function() {
            if ($(this).val()=='') $(this).val($(this).attr('data-default')); 
        });
        $( 'input[type="text"]' ).each(function( index ) {
            if ($(this).val()=='') {
			    $(this).val($(this).attr('data-default'));
			} 
        });
      }) ;
	</script>

jQuery is used, rather than simple javascript because the javascript getAttribute(‘data-function’) may not work correctly and new HTML5 data() may not work on all browsers. It is currently safest to use jQuery until HTML5 is a bit more mature.

 

Leave a Reply