Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine where focus went?

This has been asked here before, but several years ago, and there was no cross-platform solution at the time (other than the setTimeout solution, which is really not very handy).

I'd like to do onblur="foo(parm);" and have foo be able to determine which element now has focus.

I'm using regular javascript; no jQuery for this one, please.

Is that possible these days?

like image 636
Jonathan M Avatar asked Aug 17 '11 16:08

Jonathan M


People also ask

How do I find out which DOM element has the focus?

Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.

How do you know if input field is focused?

To detect if the element has the focus in JavaScript, you can use the read-only property activeElement of the document object. const elem = document. activeElement; The activeElement returns the currently focused element in the document.

How do you know if an element is focused angular?

hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.


2 Answers

You can try something like this:

function whereDidYouGo() {
    var all = document.getElementsByTagName('*');

        for (var i = 0; i < all.length; i++)
            if (all[i] === all[i].ownerDocument.activeElement)
                return all[i];
}

EDIT:

function whereDidYouGo() { return document.activeElement; }
like image 174
qwertymk Avatar answered Oct 18 '22 23:10

qwertymk


In jQuery, at the OP's request:

$(':input').blur(function() {
    $focusedElement = $(':input:focus');
    //Do stuff with $focusedElement
}
like image 31
Madara's Ghost Avatar answered Oct 18 '22 22:10

Madara's Ghost