[javascript] 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?

This question is related to javascript jquery cursor element caret

The answer is


// 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)

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.


$( document.activeElement )

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


Try this::

$(document).on("click",function(){
    alert(event.target);
    });

How is it noone has mentioned..

document.activeElement.id

I am using IE8, and have not tested it on any other browser. In my case, I am using it to make sure a field is a minimum of 4 characters and focused before acting. Once you enter the 4th number, it triggers. The field has an id of 'year'. I am using..

if( $('#year').val().length >= 4 && document.activeElement.id == "year" ) {
    // action here
}

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

I've tested two ways in Firefox, Chrome, IE9 and Safari.

(1). $(document.activeElement) works as expected in Firefox, Chrome and Safari.

(2). $(':focus') works as expected in Firefox and Safari.

I moved into the mouse to input 'name' and pressed Enter on keyboard, then I tried to get the focused element.

(1). $(document.activeElement) returns the input:text:name as expected in Firefox, Chrome and Safari, but it returns input:submit:addPassword in IE9

(2). $(':focus') returns input:text:name as expected in Firefox and Safari, but nothing in IE

<form action="">
    <div id="block-1" class="border">
        <h4>block-1</h4>
        <input type="text" value="enter name here" name="name"/>            
        <input type="button" value="Add name" name="addName"/>
    </div>
    <div id="block-2" class="border">
        <h4>block-2</h4>
        <input type="text" value="enter password here" name="password"/>            
        <input type="submit" value="Add password" name="addPassword"/>
    </div>
</form>

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to cursor

Get all dates between two dates in SQL Server Using external images for CSS custom cursors cursor.fetchall() vs list(cursor) in Python Get current cursor position in a textbox INSERT and UPDATE a record using cursors in oracle Change UITextField and UITextView Cursor / Caret Color How to get the focused element with jQuery? Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it What's the best way to iterate an Android Cursor? SQL Server: how to add new identity column and populate column with ids?

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?

Examples related to caret

How to get the focused element with jQuery? Styling text input caret How to set caret(cursor) position in contenteditable element (div)? Get contentEditable caret index position How to get the caret column (not pixels) position in a textarea, in characters, from the start?