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?
Syntax: var ele = document. activeElement; Return value: It returns the currently focused element in the document.
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.
hasFocus() : whether the document or any element inside the document has focus. document. activeElement : Property containing which element currently has focus.
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; }
In jQuery, at the OP's request:
$(':input').blur(function() {
$focusedElement = $(':input:focus');
//Do stuff with $focusedElement
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With