Coder Perfect

What is the best way to determine which DOM element has the focus?

Problem

In JavaScript, I’d like to know which element is now the focus. I’ve been searching the DOM but haven’t yet discovered what I’m looking for. Is there a way to do this, and if so, what is it?

I was seeking for this for the following reasons:

I’m attempting to make arrows and enter keys travel across a table of input components. Tab now works, however enter and arrows don’t appear to operate by default. I’ve built up the key handling, but now I need to figure out how to shift the focus to the event processing methods.

Asked by Tony Peterson

Solution #1

Use document.activeElement instead; it’s supported by all of the major browsers.

Previously, there was no way to determine which form field was in focus. Add a “focus” event handler to all fields and save the last-focused field in a variable to simulate detection in earlier browsers. Add a “blur” handler to clear the variable when the last-focused field is blurred.

You may use blur to remove the activeElement; document.activeElement.blur (). The activeElement will be changed to body.

Related links:

Answered by 7 revs, 6 users 45%

Solution #2

You can’t discover the current focused element, at least not in a browser-independent fashion, as JW stated. But if your app is IE only (some are…), you can find it the following way:

document.activeElement

It appears that IE was not quite correct; this is part of the HTML5 draft and appears to be supported by the most recent versions of Chrome, Safari, and Firefox.

Answered by Wookai

Solution #3

If you know how to utilize jQuery, you can now use it to: Just make sure you’re on version 1.6 or higher.

This statement will return the element that is currently focused.

$(":focus")

How to use jQuery to choose an element that has attention on it

Answered by William Denniss

Solution #4

Although document.activeElement is now part of the HTML5 working draft specification, some non-major/mobile/older browsers may not currently support it. You can revert to querySelector if necessary (if that is supported). That document is also worth highlighting. If no element is focused, activeElement will return document.body, even if the browser window isn’t.

The code below will work around this problem by reverting to querySelector, which provides a little better support.

var focused = document.activeElement;
if (!focused || focused == document.body)
    focused = null;
else if (document.querySelector)
    focused = document.querySelector(":focus");

The performance difference between these two approaches is also worth noting. Using selectors to query the document will always be slower than using the activeElement property. Take a look at this jsperf.com test.

Answered by Andy E

Solution #5

If the document isn’t focused (and consequently nothing in the document is focused! ), document.activeElement can nevertheless return an element.

You may prefer such behavior or it may not matter (for example, in a keydown event), but if you need to know if something is focused, you may also use document.hasFocus ().

If there is a focused element, the following will return it, otherwise null.

var focused_element = null;
if (
    document.hasFocus() &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement
) {
    focused_element = document.activeElement;
}

It’s easier to see if a particular element has focus:

var input_focused = document.activeElement === input && document.hasFocus();

To check whether anything is focused, it’s more complex again:

var anything_is_focused = (
    document.hasFocus() &&
    document.activeElement !== null &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement
);

Robustness Note: The checks against document.body and document.documentElement are included in the code because some browsers return null or one of these when nothing is focused.

It doesn’t take into account if the body> (or possibly the html>) has a tabIndex attribute and so can be focused. If you’re developing a library or something similar, you should presumably deal with this in some way.

Here’s a (heavy airquotes) “one-liner” version of getting the focused element, which is conceptually more complicated because you have to know about short-circuiting, and y’know, it obviously doesn’t fit on one line, assuming you want it to be readable. I’m not gonna recommend this one. But if you’re a 1337 hax0r, idk… it’s there. You could also remove the || null part if you don’t mind getting false in some cases. (You could still get null if document.activeElement is null):

var focused_element = (
    document.hasFocus() &&
    document.activeElement !== document.body &&
    document.activeElement !== document.documentElement &&
    document.activeElement
) || null;

You could also use events to check if a given element is focused, but this method needs setup (and possibly teardown) and, more critically, presupposes an initial state.

var input_focused = false;
input.addEventListener("focus", function() {
    input_focused = true;
});
input.addEventListener("blur", function() {
    input_focused = false;
});

You could use the non-evented method to fix the initial state assumption, but you might as well use that instead.

Answered by 1j01

Post is based on https://stackoverflow.com/questions/497094/how-do-i-find-out-which-dom-element-has-the-focus