Previous Posts


Blog Has Moved

Tuesday, July 28, 2009

Since migrating my site to Drupal I now no longer use Blogger and hence my blog has moved here.

Input Text Replace in javascript

Sunday, August 05, 2007

It is a useful thing to be able to have a input text box ( such as for a search feature on your website) that can have a default value that disappears upon the end-user inserting their cursor, and puts the default text back in if they de-select the text box without typing anything. It is a pretty simple thing to do with javascript, and can be useful from a usability standpoint (especially in conjunction with some simple css). The quickest and easiest way would be to add these two functions I have created to your javascript file.

var clearInputValue = Array();
function clearInput(thisObj){
   if(!clearInputValue[thisObj]){
      clearInputValue[thisObj] = thisObj.value;
      thisObj.value = "";
      thisObj.style.color = "black";
   }
}
function replaceInput(thisObj){
   if(thisObj.value == ""){
      thisObj.value = clearInputValue[thisObj];
      thisObj.style.color = "#999999";
      clearInputValue[thisObj]= false;
   }
}
Then add onblur="replaceInput(this);" onfocus="clearInput(this);" to your input tag. The replaceInput and clearInput functions assume the text is light grey (#ccc) to begin with and make the text black once the user starts typing something and if they de-select the text box without typing anything it puts the default text back in and sets the text color back to light grey. Beyond this I suggest using css to let users know when the input is in focus since that little blinking cursor can often be hard to see. So in your css file you may want to include something like this (assuming your text box has a class of "searchInput"):
input.searchInput{border:1px solid #ccc; color:#ccc;}
input.searchInput:hover{border:1px solid #699A2F;}
input.searchInput:focus{background:#f8f6c3; border:1px solid #699A2F;}
But if you want to go all the way and use unobtrusive javascript (and I recommend that you do) techniques then I would highly recommend using Ben Nolan's excellent lightweight javascript file for unobtrusively adding event listeners to elements in the DOM. Behaviour is an awesome resource. Using Behaviour, instead of adding the onfocus and onblur inline in your xhtml, simply include the behaviour.js file via a script tag at the top of your page. Then in your javascript file add:
var myrules = {
    'input.searchInput' : function(element){
       element.onfocus = function(){
          clearInput(element);
       },
       element.onblur = function(){
          replaceInput(element);
       }
    }
};

Behaviour.register(myrules);

Labels:

0 Comments:

Post a Comment

<< Home