.focus()


.focus( handler )Возвращает: jQuery

Описание: Устанавливает обработчик получения фокуса, либо, запускает это событие.

  • Добавлен в версии: 1.0.focus( handler )

    • handler
      Тип: Function( Event eventObject )
      A function to execute each time the event is triggered.
  • Добавлен в версии: 1.4.3.focus( [eventData ], handler )

    • eventData
      Тип: Anything
      An object containing data that will be passed to the event handler.
    • handler
      Тип: Function( Event eventObject )
      A function to execute each time the event is triggered.
  • Добавлен в версии: 1.0.focus()

    • This signature does not accept any arguments.
  • This method is a shortcut for .on( "focus", handler ) in the first and second variations, and .trigger( "focus" ) in the third.
  • The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
  • Elements with focus are usually highlighted in some way by the browser, for example with a dotted line surrounding the element. The focus is used to determine which element is the first to receive keyboard-related events.

Attempting to set focus to a hidden element causes an error in Internet Explorer. Take care to only use .focus() on elements that are visible. To run an element's focus event handlers without setting focus to the element, use .triggerHandler( "focus" ) instead of .focus().

For example, consider the HTML:

1
2
3
4
5
6
7
<form>
<input id="target" type="text" value="Field 1">
<input type="text" value="Field 2">
</form>
<div id="other">
Trigger the handler
</div>

The event handler can be bound to the first input field:

1
2
3
$( "#target" ).focus(function() {
alert( "Handler for .focus() called." );
});

Now clicking on the first field, or tabbing to it from another field, displays the alert:

Handler for .focus() called.

We can trigger the event when another element is clicked:

1
2
3
$( "#other" ).click(function() {
$( "#target" ).focus();
});

After this code executes, clicks on Trigger the handler will also alert the message.

The focus event does not bubble in Internet Explorer. Therefore, scripts that rely on event delegation with the focus event will not work consistently across browsers. As of version 1.4.2, however, jQuery works around this limitation by mapping focus to the focusin event in its event delegation methods, .live() and .delegate().

Дополнительные замечания:

  • As the .focus() method is just a shorthand for .on( "focus", handler ), detaching is possible using .off( "focus" ).

Примеры использования