1

Is it possible to find the element that currently has the focus in a cross-browser way?

In IE, it is possible to do $(x).blur(function(evt) { alert('Focus goes to ' + evt.toElement.id); }); and I need to do something similar in other browsers.

As an alternative, if its possible, I could do a setTimeout and then investigate the currently focused element, but I don't know to do that either.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
erikkallen
  • 33,800
  • 13
  • 85
  • 120
  • Possible duplicate of [When onblur occurs, how can I find out which element focus went \*to\*?](http://stackoverflow.com/questions/121499/when-onblur-occurs-how-can-i-find-out-which-element-focus-went-to) – Alex Angas Jan 08 '16 at 01:22

1 Answers1

0

You could just remember what was focused in a variable. Variable scope in JS works cross-browser :)

(function($){

var focused;
$(commonParentForElements).on('focus','input',function(e){
  focused = e.target;
}).on('blur','input',function(e){
  //do stuff with focused
  //when done, clean up
  focused = null;
})

})(jQuery);
naugtur
  • 16,827
  • 5
  • 70
  • 113