Setting Focus to a Text Input in Firefox with jQuery
Thursday, June 17th, 2010 | Author: dbatesx

If you're new here, you may want to subscribe to my RSS feed. Thanks for visiting!

On one of the sites I’m working on, there’s a log-in page that’s usually presented in an iframe. I wanted to set focus to the username field when the form was loaded, so I added

$(function() { $('#email').focus(); }

to the <script> section.

(There is also code that resizes the iframe to accommodate the height of the content)

This worked fine in IE7/8 and Chrome.

However, when the page would load in Firefox, the top part of the login form wasn’t displayed; rather, it was rendered, but hidden as if you had scrolled down the iframe to the input field that was in focus (although scrolling is turned off for the iframe).

After enclosing the .focus() in a setTimeout(), the whole form would show correctly, and the field was in focus as desired:

 $(function() {
   setTimeout( // Need the setTimeout wrapper for FF, or top of page isn't visible...
     function() {
       if ($('#email').val() > '')
         $('#password').focus();
       else
         $('#email').focus();
     }
     , 1);
 });