Jesse is a developer from Calgary, Alberta who specializes in websites, Flash and iOS development.

Autoblur Javascript Object

Posted on 1 Jan 2009 by Jesse Knowles in HTML | Comments

I hate coding things twice and every once in a while I seem to need something that automatically clears the default value in an input text field for a form. So I decided to write a javascript object that would make life incredibly easy for me. And now its all yours if you have a need for something like this. Here is an example of what I'm talking about. You will notice that when you click in the text field it clears the default text, and if you click away from the text field it will return the default text only if you haven't entered anything. it's pretty basic but annoying to always have to code again and again so I have added it to my utils.js file that I use throughout my projects. Here's the code...

This javascript needs to be included or somewhere on your html page...

function autoBlur(_formId, _fieldId) {
var __fieldObj = document.getElementById(_formId)[_fieldId];
var __initValue = __fieldObj.value;

__fieldObj.onfocus = function() {
  if(__fieldObj.value == __initValue) __fieldObj.value = "";
}
__fieldObj.onblur = function() {
  if(__fieldObj.value == "") __fieldObj.value = __initValue;
}
}

Now, your form probably looks something like this...

<form id="shipping_search" method="post">
   <div class="inline"><input type="text" name="search" id="search" value="Enter Store Name" /></div>
</form>

Now just initialize the javascript object anywhere after your end form tag and pass it the form id and the input field id and the magic will happen.

<form id="shipping_search" method="post">
   <div class="inline"><input type="text" name="search" id="search" value="Enter Store Name" /></div>
</form>
<script type="text/javascript">autoBlur('shipping_search', 'search')</script>

Let me know how it works for you. Enjoy!

Recent Pics