How to check focus on elements and windows?

I want to find which element is in focus. Also, when a user opens multiple windows / tab, I would like to know which window / tab is in focus.

+1
source share
3 answers

In normal 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 receives focus, we save this element in a variable, and when an element loses focus, we reset the variable.

HTML 5 has a special attribute for accessing the currently concentrated element:

var focusedElement = document.activeElement;
+2
source

Using jQuery, you can use this to find the focus:

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

- DOM , , .

. jQuery , -.

Javascript.

+1

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

0
source

All Articles