Unobtrusive Input Clear on Focus

10-02-2008 3

I’ve seen a lot of functions out there that handle the much adored input clear on focus. This is a nice feature to have on your site especially on search boxes. Also, according to usability standards, you are not supposed to leave any input field blank. The value of your input fields and textareas should describe in detail what it is the user should be putting into the form field.

There are many ways to go about accomplishing this feature. The best way to accomplish this is with this code that I found at Perishable Press. Many others have chosen to do this by adding inline JavaScript to their HTML markup, and we all know that that is a big no-no in today’s world. Today, with the use of the powerful Document Object Model, or DOM, we are able to manipulate our markup without actually changing anything.

Let’s get down to business. Now if you’re like me, you’ve found this article from Google and you’re working on a project and you’re in a rush, so here’s the code so you can continue your project. Put this into an external file named inputclear.js and upload it to your server.

function init() {
 var inputs = document.getElementsByTagName('input');
 for(var i=0; i < inputs.length; i++) {
  inputs[i].setAttribute('rel',inputs[i].defaultValue);
  inputs[i].onfocus = function() {
   if (this.value == this.getAttribute('rel') && this.getAttribute('type') != 'submit' && this.getAttribute('type') != 'reset') {
    this.value = '';
   } else {
    return false;
   }
  }
  inputs[i].onblur = function() {
   if(this.value=='' && this.getAttribute('type') != 'submit' && this.getAttribute('type') != 'reset') {
    this.value = this.getAttribute('rel');
   } else {
    return false;
   }
  }
  inputs[i].ondblclick = function() {
   this.value = this.getAttribute('rel')
  }
 }
}
 
if(document.childNodes) {
 window.onload = init;
}

Afterwards, add link to this javascript in your header with a script tag. Don’t forget to change the location of the javascript file to where you uploaded inputclear.js.

<script src="http://example.com/js/inputclear.js" type="text/javascript"><!--mce:0--></script>

This code can also be used to clear textareas by changing this line:

var inputs = document.getElementsByTagName('input');

To this:

var inputs = document.getElementsByTagName('textarea');

Responses to “Unobtrusive Input Clear on Focus”

Leave a reply