Problem with input focus on Safari

I had a javascript hic­cup, and I think the solu­tion may be help­ful to others.

The basic setup is this:

Lim­ited space means no room for labels in a login form. So instead we used a pre­set value in the input ele­ments, like so:

 
<input value="Username" name="username" type="text" />
<input value="Password" name="password" type="text" />
 

Which looks like this:

The easy way to blank out the descrip­tive text is to use the onfo­cus event like so:

 
onfocus="this.value=''"
 


But this is not enough for the pass­word input, because we do not want to reveal a user’s pass­word as it is typed. We must change the input type to pass­word. This causes the input ele­ment to lose focus, so we set it again after chang­ing type:

 
onfocus="this.value='';this.type='password';this.focus();"
 

Cool. But it doesn’t work in Safari. Tab­bing from the user­name field to the pass­word field does not work as expected. The input ele­ment looks focused but it won’t accept any key­board input until you click in the field.

Solu­tion — use the select method instead of focus:

 
onfocus="this.value='';this.type='password';this.select();"
 
 
<input onfocus="this.value=''" value="Username" name="username" type="text" />
<input value="Password" name="password" type="text" onfocus="this.value='';this.type='password';this.select();" />
 

I hope that helps some­body out there in Google-vania.

[UPDATE 22 Feb 2008]
Well, it turns out that this works well for Safari and Fire­fox, but breaks in ie/win (shocker.) so I was forced to go another route. Inter­net Explorer will not allow you to change the type of an input ele­ment with Javascript, so I made the input a pass­word ele­ment to begin with. Using css, set a back­ground image that says “Pass­word” and then, on focus, remove the back­ground image. Voilà.

[UPDATE 16 Dec 2009]
I just came across a very inter­est­ing tech­nique on Smash­ing Magazine’s blog. It involves plac­ing a field’s label behind the field and fad­ing it on focus. The label does not dis­ap­pear com­pletely until the user actu­ally starts typ­ing. Very ele­gant solu­tion and it min­i­mizes cases where a user may for­get what a field’s pur­pose was because the descrip­tive text has dis­ap­peared.
http://www.smashingmagazine.com/2009/12/16/stronger-better-faster-design-with-css3/

Like it? Tweet it!

This entry was posted in Code and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted 26 May 2010 at 6:05 pm | Permalink

    prob­lem seems fixed in safari 4 on mac, at least your exam­ple works as expected

Post a Comment

Your email is never published nor shared. Required fields are marked *

Connect with Facebook

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>