26

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?

ggorlen
  • 33,459
  • 6
  • 59
  • 67
Jigar Parekh
  • 5,955
  • 5
  • 42
  • 64

2 Answers2

13

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
  • 298,938
  • 77
  • 579
  • 623
6

@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" />
OfirD
  • 7,020
  • 2
  • 33
  • 68