What Happens When You Blur A Dom Element
Solution 1:
The closest thing to a specification about this is probably the description of focus in HTML5 CR (which is work in progress, “a draft document and may be updated, replaced or obsoleted by other documents at any time”, but in practice close to a consensus). It says: “There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element, if there is one, or else at the Document's root element, if there is one. If there is no root element, key events must not be fired.”
Since the blur()
method is defined (in DOM 2 HTML spec) simply as removing focus, it means leaving a page in a state where no element is focused. But this may look like the body
element were focused: if you have, say, a keypress
attribute on it, it gets triggered. This however differs from the focused state. For example, in this situation, the body
element does not match the CSS selector :focus
.
The conclusion is that you should normally avoid using blur()
and do focus()
on some suitable focusable element instead, as suggested in other answers. An exception is a situation where you just want to discard all keyboard events. Then blur()
is OK, provided that your code does not assign any keyboard event handlers to the body
element.
Solution 2:
If you just want to make sure that one element gets focused when another gets blurred:
/* Javascript */var root = document.getElementById("root");
var p1 = document.getElementById("p1");
var p2 = document.getElementById("p2");
p2.addEventListener('blur', function(event) {
p1.focus();
activeEl();
}, false);
p2.focus();
activeEl();
functionactiveEl() {
console.log("focused element = ");
console.log(document.activeElement);
}
Fiddle: http://jsfiddle.net/2cWcA/
You could extend this so that when any element is blurred, it's parent's focus
method is called.
Solution 3:
My understanding is that blur
just means unfocus. In other words, the focused element loses focus, and it's undefined what, if anything, gains focus. The fact that activeElement
becomes body
is probably just a side effect. Rather than setting it to null
it's set to the body, to indicate that the document in general still has focus.
Solution 4:
Actually document.ActiveElement() focuses an element.
In javascript focus is done like document.getElementById('myAnchor').focus()
MoreOver the focus event triggers when a visitor focuses on an element.
Not all elements are focusable by default. For example, INPUT and all types or form fields support this event, A supports it. As a counterexample, DIV doesn’t support focus.
The list of elements types which support focusing is slightly different between browsers.
Thanks
Post a Comment for "What Happens When You Blur A Dom Element"