Using jQuery, how can I get the input element that has the caret's (cursor's) focus?
Or in other words, how to determine if an input has the caret's focus?
The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.
jQuery focus() Method The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.
var el = document. getElementById('myElement'); el. matches(':focus'); // If it has focus, it will return true.
// Get the focused element: var $focused = $(':focus'); // No jQuery: var focused = document.activeElement; // Does the element have focus: var hasFocus = $('foo').is(':focus'); // No jQuery: elem === elem.ownerDocument.activeElement;
Which one should you use? quoting the jQuery docs:
As with other pseudo-class selectors (those that begin with a ":"), it is recommended to precede :focus with a tag name or some other selector; otherwise, the universal selector ("*") is implied. In other words, the bare
$(':focus')
is equivalent to$('*:focus')
. If you are looking for the currently focused element, $( document.activeElement ) will retrieve it without having to search the whole DOM tree.
The answer is:
document.activeElement
And if you want a jQuery object wrapping the element:
$(document.activeElement)
$( document.activeElement )
Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With