1

I want to find which element is on focus. Also, when a user opens multiple windows/tab, i'd like to know which window/tab is on the focus.

Paul
  • 954
  • 19
  • 34

3 Answers3

2

In plain JavaScript (i.e. without any frameworks like jQuery, MooTools, etc.):

var focusedElement;

document.addEventListener("focus", function(e) {
    focusedElement = e.target;
}, true);

document.addEventListener("blur", function(e) {
    focusedElement = null;
}, true);

Basically, whenever an element gains focus, we save that element to a variable, and when the element loses focus, we reset the variable.

In HTML 5, there's a specific attribute for accessing the currently focused element:

var focusedElement = document.activeElement;
Steve Harrison
  • 121,227
  • 16
  • 87
  • 72
  • just be aware that as the user clicks around in the document text, (not elements) the focus handler will be called with e.target set to the document on each click, with no intervening blur handler call. – Ed. Nov 12 '09 at 15:45
1

Using jQuery, you can use this to find focus:

$("body").bind("onfocus", function (e) {
  alert("focus: " + e.target); // e.target is the element with focus
});

You need only one handler using event delegation - the event percolates up the DOM tree until it is handled, so you can make do with one handler for the whole document.

See jQuery documentation for their event object and event functions, it makes it much simpler to do this in a cross-browser fashion.

Multiple browser windows or tabs is not accessible from Javascript.

j-g-faustus
  • 8,801
  • 4
  • 32
  • 42
0

Here's a tip. Anyway, you have to add event handler for each input element on a page. Only alternative is IE-only: document.activeElement

terR0Q
  • 1,369
  • 8
  • 17