Focusing a Text Input on Page Load - J Query

You have a login form on your home page, and you’d like the username text input to be focused on page load.


Use the jQuery $(selector).focus() method:


Using $(document).ready() should be fast enough. However, in situations like retrieving a huge HTML file over a slow connection, the cursor might focus later than desired—the user could have already entered her username and could be in the process of typing her password when $(document).ready() executes and puts her cursor back in the username text input. How annoying! In this case you could use inline JavaScript after the <input>tag to make focus immediate:

Or, if you prefer to keep your code together in the $(document).ready() block, you can check to see whether the text input has any text in it before giving it focus:

What will happen when JavaScript is disabled? The user will have to manually click into the text input to start typing.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics