Reputation: 48733
I have:
document.body.addEventListener("keydown", function(event) {
var key = event.keyCode || event.which;
switch (key) {
case 38: ui.action.up(); break;
case 40: ui.action.down(); break;
case 37: ui.action.left(); break;
case 39: ui.action.right(); break;
}
return false;
});
in code that implement 2048 game.
I have user forms and want to exit from handler if document.activeElement
point to input
or textarea
or select
as handler break ability to perform normal edit operation for users.
Currently I see two paths for such check:
["INPUT", "TEXTAREA", "SELECT"].indexOf(document.activeElement.nodeName) > -1
and:
document.activeElement instanceof HTMLInputElement
|| document.activeElement instanceof HTMLTextAreaElement
|| document.activeElement instanceof HTMLSelectElement
What is a portable way and what is the best that confirm to HTML 5 standard and what is a shortest one?
UPDATE I try 3rd strategy - check for properties that unique for editable elements. From standard http://www.w3.org/TR/DOM-Level-2-HTML/html.html with help of undescore.js
:
var good = _.intersection(Object.keys(HTMLInputElement.prototype),
Object.keys(HTMLTextAreaElement.prototype),
Object.keys(HTMLSelectElement.prototype))
var bad = _.union(Object.keys(HTMLObjectElement.prototype),
Object.keys(HTMLAnchorElement.prototype),
Object.keys(HTMLDivElement.prototype),
Object.keys(HTMLButtonElement));
console.log(_.difference(good, bad));
I get the list:
"autofocus", "disabled", "required", "value"
So I stop with:
if (document.activeElement.value) { ... }
checks!
Upvotes: 0
Views: 1349
Reputation: 48733
This answer confirms standards, elegant, but may lack of portability:
if (document.activeElement.value) { ... }
Upvotes: 1