jQuery has several focus related events – focus, focusin, and focusout. The focus event occurs when an element gets focus, such as when the element is selected by a mouse click or by using the tab key on the keyboard to navigate to the target element.
The focus() method triggers the focus event, or specifies a function to run when a focus event occurs. The focusin event is similar to the focus event, but unlike the focus() method, the focusin() method triggers if any child element gets focus. The same is true with the focusout() method.
Syntax
$(selector).focus(function()) $(selector).focusin(function()) $(selector).focusout(function())
Focus Example
In the following jQuery example, when a user clicks on an input element or uses the tab key, the currently selected input element will trigger the focus() method.
In the example below, when this event is triggered, a different CSS set of properties are applied to the element that has the focus event attached. When the user clicks on a different input element, the focusout() method is triggered.
First Name | |
Last Name | |
Department |
Focusin and Focusout Example
In the following jQuery example, when a user clicks on a child element of the parent element, the focusin event that is attached to the parent is executed.
In the example below, the focusin() method triggers and executes a function to modify the CSS background-color property of the parent element.
First Name | |
Last Name | |
Department |