Problem with input focus on Safari

I had a javascript hiccup, and I think the solution may be helpful to others.

The basic setup is this:

Limited space means no room for labels in a login form. So instead we used a preset value in the input elements, like so:

  1.  
  2. <input value="Username" name="username" type="text" />
  3. <input value="Password" name="password" type="text" />
  4.  

Which looks like this:



The easy way to blank out the descriptive text is to use the onfocus event like so:

  1.  
  2. onfocus="this.value=''"
  3.  


But this is not enough for the password input, because we do not want to reveal a user's password as it is typed. We must change the input type to password. This causes the input element to lose focus, so we set it again after changing type:

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

Cool. But it doesn't work in Safari. Tabbing from the username field to the password field does not work as expected. The input element looks focused but it won't accept any keyboard input until you click in the field.



Solution -- use the select method instead of focus:

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


I hope that helps somebody out there in Google-vania.

[UPDATE 22 Feb 2008]
Well, it turns out that this works well for Safari and Firefox, but breaks in ie/win (shocker.) so I was forced to go another route. Internet Explorer will not allow you to change the type of an input element with Javascript, so I made the input a password element to begin with. Using css, set a background image that says "Password" and then, on focus, remove the background image. Voilà.

[UPDATE 16 Dec 2009]
I just came across a very interesting technique on Smashing Magazine's blog. It involves placing a field's label behind the field and fading it on focus. The label does not disappear completely until the user actually starts typing. Very elegant solution and it minimizes cases where a user may forget what a field's purpose was because the descriptive text has disappeared.
http://www.smashingmagazine.com/2009/12/16/stronger-better-faster-design-with-css3/

One thought on “Problem with input focus on Safari

Leave a Reply