Cover Image for jQuery focusin() method
102 views

jQuery focusin() method

The focusin() method in jQuery is used to attach an event handler function to elements when they gain focus or when any of their child elements gain focus. It is similar to the focus() method but with a subtle difference: focusin() bubbles the event up through the DOM hierarchy, whereas focus() does not.

Here’s the basic syntax of the focusin() method:

$(selector).focusin(handler)

Parameters:

  • selector: The selector for the elements to attach the event handler to.
  • handler: The function to be executed when the focusin event occurs on the selected elements.

Return Value:
The focusin() method returns the same jQuery object to support method chaining.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery focusin() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <input type="text" id="inputField" placeholder="Enter your name">

    <script>
        $(document).ready(function() {
            $("#inputField").focusin(function() {
                $(this).css("border", "2px solid blue");
            });
        });
    </script>
</body>
</html>

In this example, we have an input field with the id inputField. When the input field or any of its child elements gain focus (e.g., when you click inside the input field), the focusin() event is triggered. We use the focusin() method to attach an event handler that changes the border color of the input field to blue.

Please note that the focusin() method can be particularly useful when you want to handle focus-related events for both the selected elements and their descendants. The event will bubble up from the descendant elements to the selected elements, allowing you to handle the event at a higher level in the DOM tree.

Keep in mind that as of jQuery version 3.0, the focusin() and focusout() methods were deprecated in favor of using the more standard focus and blur events with the on() method. However, they are still available for backward compatibility and can be used if needed.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS