3

How can I test if a HTML element is focused? I want to execute a code when a dropdown select list ISN'T selected. So, If you click on the document, anywhere else in than the select list, a JavaScript unselect all of it's elements.

This statement doesn't worked:

var items=document.getElementById("items");
items.focused==false;

I hope somebody can help me out.

qwertynl
  • 3,912
  • 1
  • 21
  • 43
kukko
  • 643
  • 10
  • 21
  • 2
    Not an exact duplicate, but very close: http://stackoverflow.com/questions/483741/how-to-determine-which-html-page-element-has-focus – p.s.w.g Jan 06 '14 at 15:22
  • 1
    You can use the event `onblur`, which gets called when something looses focus – RononDex Jan 06 '14 at 15:23
  • Check if the item is `=== document.activeElement` – crush Jan 06 '14 at 15:24
  • What do you mean by `a dropdown select list ISN'T selected`? Because by default the first `option` in the `select`-list gets selected even if it is not provided the `selected` property. So would you please elaborate? – Rajesh Paul Jan 06 '14 at 16:22

1 Answers1

4

Newer versions of JavaScript allow this:

if( items.matchesSelector(":focus"))

But for older browsers you can try:

if( document.querySelector("#items:focus"))

However this won't work in IE 7 and older.

If you require support for these, then I would suggest something like this for your handler:

// some means of attaching a handler(evt) {
evt = evt || window.event;
var target = evt.srcElement || evt.target;
while(target) {
    if( target.id == "items") return true;
    target = target.parentNode;
}
// #items is not the target. Do something.
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592