Time for action – setting focus to the first field

We'll keep working with the sample form we set up in the last example. Here's how to set the focus to the first field in the form.

  1. Open up your empty scripts.js file and add a document ready statement.
      $(document).ready(function(){
        //code goes here
      });
  2. Next up, we want to select the first field in our form. There are many different ways to go about that. In this case, I'm going to use the id of the first form element.
      $(document).ready(function(){
        $('#username');
      });
  3. All that's left to do is call the focus() method for that element.
      $(document).ready(function(){
        $('#username').focus();
      });

    Now if you refresh the page in the browser, you'll see that the cursor is blinking in the Username field of ...

Get jQuery for Designers Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.