Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

document.activeelement returns body

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?

like image 279
Jigar Parekh Avatar asked Jul 02 '12 19:07

Jigar Parekh


2 Answers

Between leaving the old element and entering the new element the active element is indeed the document/body itself.

Demo: http://jsfiddle.net/u3uNP/

like image 126
ThiefMaster Avatar answered Oct 09 '22 06:10

ThiefMaster


@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" />
like image 39
OfirD Avatar answered Oct 09 '22 06:10

OfirD