views:

153

answers:

3

On Chris Coyer's site he uses a nice little search box. I am curious to know how you get the text in the search box to disappear and reappear when you click out of the box.

Thanks to a helpful person on this forum I use the following to have the text disappear when I click in the box:

<input type="text" value="Search" onfocus="if (this.value=='Search') this.value='';"/>

Also, in Safari there is a nasty border around the input field when I click inside. What is the code for getting rid of that?

Thanks!

+1  A: 

I do not believe you can remove the border in Safari, though open to corrections.

To get the text to appear again when you click out of the search box, you can use this:

<input onblur="if (this.value == '') this.value ='Search';" />
A S
You actually can remove the border in safari.
fmz
+2  A: 

To reset the Search text, add an onblur:

onblur="if (this.value=='') this.value='Search';"

so your input box becomes:

<input type="text" value="Search" onfocus="if (this.value=='Search') this.value='';" onblur="if (this.value=='') this.value='Search';"/>

also, for the Safari border, add this in your css:

input[type=text]:focus,
input[type=password]:focus {
    outline: 0 none;
}
jao
Excellent help! Thanks.
fmz
however, please notice that for accessibility reasons it is not recommended to remove the outline: http://webaim.org/blog/plague-of-outline-0/
jao
+2  A: 

You can get rid of static value duplication if you make use of the defaultValue property

Compare this

<input type="text" value="Search" onblur="if ('' == this.value) this.value = 'Search';" onfocus="if ('Search' == this.value) this.value='';"/>

which has three instances of the statc string "Search", to this

<input type="text" value="Search" onblur="if ('' == this.value) this.value = this.defaultValue;" onfocus="if (this.defaultValue == this.value) this.value='';"/>

which has only one.

But if you really want to take this to the "next level", you could implement something like the nearly canonical labels.js. The code is really old now, having been authored in 2002 (I think), but the concept is sound and it's basic concept has since been put to good use with modern frameworks.

Peter Bailey
Nice. Didn't know about the .defaultValue property.
Saajid Ismail