kukko
kukko

Reputation: 653

Detect element ISN'T selected

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.

Upvotes: 3

Views: 869

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

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.

Upvotes: 4

Related Questions