Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the focused element with jQuery?

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?

like image 433
dave Avatar asked Jun 30 '12 21:06

dave


People also ask

How do you focus an element in jQuery?

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.

What is focus function in jQuery?

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.

How do you check an element is focus or not?

var el = document. getElementById('myElement'); el. matches(':focus'); // If it has focus, it will return true.


2 Answers

// 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) 
like image 115
gdoron is supporting Monica Avatar answered Sep 20 '22 08:09

gdoron is supporting Monica


$( document.activeElement ) 

Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation

like image 30
Grilse Avatar answered Sep 22 '22 08:09

Grilse