Here is my HTML and JS:
function invokeFunc() {
// ajax request
alert(document.activeElement);
// this returns body element in firefox, safari and chrome.
}
<input id="text1" tabindex="1" onblur="invokeFunc()" />
<input id="text2" tabindex="2" onblur="invokeFunc()" />
I am trying set focus onblur on text boxes with proper tabindex set.
When I invoke the JavaScript function onblur and try to get document.activeElement
it always returns the body element instead of the active element where focus is.
How can I return the active element rather than the body?
Between leaving the old element and entering the new element the active element is indeed the document/body itself.
Demo: http://jsfiddle.net/u3uNP/
@ThiefMaster explained the reason, and I want to add a solution for getting the newly focused element:
Use focusout
instead of onblur
, and then utilize relatedTarget
property:
const inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; ++i) { inputs[i].addEventListener('focusout', (event) => { console.log('newly focused element:', event.relatedTarget); }); }
<input id="text1" tabindex="1" /> <input id="text2" tabindex="2" />
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