javascripthtmltabindex

document.activeElement returns body in onblur handler


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?


Solution

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

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