HTML5 Placeholders With jQuery

HTML 5 brings many new features to the browser including a lot of enhancements to the way forms are created and handled. One of my favourite features is the introduction of the placeholder attribute, this allows the display of  some text in a text input field or text area until the element is brought into focus. This allows the addition of small tips or related prompts to give the user a better understanding of what is required as input.

A lot of web browsers already support the attribute but others do not (I am looking at you Internet Explorer!), but fortunately there is the the Jquery HTML5 placeholder plug-in. Written by Mike Taylor this jQuery based plug-in will first test if the placeholder attribute is supported by the user’s browser an if not then try to replicate the functionality using javascript. The plug-in is very easy to use simply download the source from GitHub, grab the jQuery library, load into the head of your page and then just activate.

<script src="jquery.js" type="text/javascript"></script>
<script src="html5_placeholders.js" type="text/javascript"></script>
<script>
  $(function(){
    $(':input[placeholder]').placeholder();
  });
</script>

You should now be able to add placeholder attributes to the text form elements throughout your site and have them be backward compatible with incompatible browsers eg

<input type="text" name="user_name" placeholder="enter username">

 

Leave a Reply

Your email address will not be published. Required fields are marked *