jquery
  1. jquery-focus

jQuery focus()

The focus() method in jQuery is used to set focus on a particular element. When executed, it shifts the user’s cursor or focus to the specified element on the web page.

Syntax

$(selector).focus();

Here, selector refers to the element you want to set focus on.

Use

The focus() method is useful when you want to improve the user experience of your web page by guiding the user's attention to specific web page elements.

Example

Here is an example of using the jQuery focus() method to set focus on an input element:

<!DOCTYPE html>
<html>
  <head>
    <title>jQuery focus() Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  </head>
  <body>
    <label for="name">Enter your name:</label>
    <input type="text" id="name" name="name" autofocus />
    <br />
    <button id="button">Submit</button>
    <script>
      $(document).ready(function () {
        $("#name").focus();
      });
    </script>
  </body>
</html>
Try Playground

In this example, the jQuery focus() method is used on the input element with the ID of "name". When the page loads, the focus is automatically set on this element, allowing the user to begin typing without having to manually set the focus themselves.

Summary

In conclusion, the jQuery focus() method is a powerful tool that can improve the user experience of your web page by guiding the user's attention to specific web page elements. By using the simple syntax and examples provided, you can easily add this feature to your website and help make it more user-friendly.

Published on: