CancelImage Upload

How to make text disappear inside a textbox on focus with JavaScript

This is a rather elegant solution for crowded websites with not much space. Particularly to place "Enter your comment here:" in front of a textarea, or "Enter Username:" before a textbox.

Instead you can have your user suggestion placed inside the text, and with the following JavaScript code make it disappear on focus, and re-appear on mouseout if the textbox has been left empty.

First we will have a look at the HTML code. As you can see we have set the textbox to call upon the JavaScript function areaOnFocus onfocus and areaOnBlur onblur, both passing on the name of the textbox, text1, and the value on which the box should either be set to empty on focus, or be included again if the box is left empty on blur:

<input value="Enter Name" onfocus="areaOnFocus(text1, 'Enter Name')" onblur="areaOnBlur(text1, 'Enter Name')" type="text" name="text1">

Next up are the two JavaScript Functions: areaOnFocus() and areaOnBlur()

Area on focus first checks that text1's value is indeed the same as the text specified on which the textbox should be emptied. After all, the last thing you want is for your textbox to become empty regardless of its content:

function areaOnFocus(element, inputText)
{

     if(element.value == inputText)
     {

          element.value='';

     }

}

And here is the opposite, areaOnBlur(). When the user's curser leaves the box this function is called upon, and if the box is indeed empty, the specified text will be placed into text1:

function areaOnBlur(element, inputText)
{

     if(element.value=='')
     {

          element.value = inputText;

     }

}

And that is all there is too it!

Login
Want to leave a comment?

No problem. Just enter your email and password below.


register | home | reminder

myDesignTool Networking • www.mydesigntool.cominfo@mydesigntool.com