30

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
  • 44,755
  • 7
  • 76
  • 106
Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64

2 Answers2

16

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
  • 310,957
  • 84
  • 592
  • 636
14

@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
  • 9,442
  • 5
  • 47
  • 90