393

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?

General Grievance
  • 4,555
  • 31
  • 31
  • 45
dave
  • 14,991
  • 26
  • 76
  • 110
  • Possible duplicate http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus – bart s Jun 30 '12 at 21:57
  • Possible duplicate: http://stackoverflow.com/questions/516152/how-to-select-an-element-that-has-focus-on-it-with-jquery/9875020#9875020 – Sam Shiles Jan 30 '13 at 13:20

8 Answers8

817
// 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)
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 2
    but wait, how do i get teh element that has the caret? – dave Jun 30 '12 at 22:16
  • @dave. What do you mean _"has the caret"_ ? focused? the mouse is on it? – gdoron Jun 30 '12 at 22:18
  • well here is my situation: when i click a particular element, i want to place a character in the last focused input text element. Basically the element that had focus last or right before clicking that particular element. – dave Jun 30 '12 at 22:20
  • 1
    @dave. It can't be done. I think only IE has this feature, but you're asking now a different question, you should do it in a new question. – gdoron Jun 30 '12 at 22:23
  • @dave in this case you should use `blur` try this `$('input[type="text"]').on('blur', function() { // do something here })` – Ram Jun 30 '12 at 22:25
  • 4
    I like how you used $ prefixed variable name, `$focused`, as I assume you do that to denote the var is a jquery object. TYVM. – Valamas Jul 10 '13 at 01:35
  • OSX typically doesn't give non-text inputs "focus", so document.activeElement generally doesn't work for buttons, radios, etc. –  Mar 31 '14 at 15:37
  • @SoldOutActivist that's not the case for Safari, Chrome, or Firefox (at least not currently) All three browsers correctly return the currently focused button via `document.activeElement` – Brad Kent Apr 10 '17 at 18:30
42
$( document.activeElement )

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

Stacked
  • 6,892
  • 7
  • 57
  • 73
Grilse
  • 3,491
  • 2
  • 28
  • 35
6

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>
bumbumpaw
  • 2,522
  • 1
  • 24
  • 54
ucdream
  • 691
  • 1
  • 7
  • 18
5

Try this:

$(":focus").each(function() {
    alert("Focused Elem_id = "+ this.id );
});
Adil Malik
  • 6,279
  • 7
  • 48
  • 77
  • Yes, that's why this loop will have only one iteration. alert is just to demonstrate the example. If you have this variable, you can everything with the element that you want. – Adil Malik Jun 30 '12 at 22:08
  • How is it possible to focus more than one element? – Andreas Furster Sep 15 '14 at 12:36
  • @AndreasFurster you're right. There will always be only one iteration in this loop. This might not be the best way to achieve the goal, but it works. – Adil Malik Sep 15 '14 at 16:13
  • See the accepted answer to learn why this is the worst / least efficient way to do it. (unnecessary `.each` non-withstanding) – Brad Kent Apr 10 '17 at 18:33
3

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
}
Tom aka Sparky
  • 76
  • 1
  • 11
1

$(':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.

Travis Heeter
  • 13,002
  • 13
  • 87
  • 129
1

Try this::

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

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

if ($('#inputId').is(':focus')) {
    //your code
}
Basel Issmail
  • 3,847
  • 7
  • 20
  • 36