4

I wish to determine when an HTML element and it's children lose focus when the user clicks away from the element. Eg:

<div id="boxA">
  <ul>
    <li>x</li>
    <li>y</li>
    <li>z</li>
  </ul>
</div>
<div id="boxB">
...
</div>

At the moment I have:

$("#boxA").live('blur', function() { hideFunction();  });

However, this does not work. If I click any element within Box A, it loses focus, but I only want it to happen when Box B is clicked or anywhere else on the page.

Edit & Solution

I found this solution on Stack Overflow. It works for me:

Use jQuery to hide a DIV when the user clicks outside of it

Community
  • 1
  • 1
amburnside
  • 1,943
  • 5
  • 24
  • 43

5 Answers5

3

You could try listening on the focusout event and then checking if the current element with focus is a child of your container, like this:

$('#boxA').on('focusout', function (e) {
    setTimeout(function () { // needed because nothing has focus during 'focusout'
        if ($(':focus').closest('#boxA').length <= 0) {
            hideFunction();
        }
    }, 0);
});
Spig
  • 458
  • 1
  • 5
  • 16
2

Try giving your div a tabindex attribute:

<div id="boxA" tabindex="0">
  <ul>
    <li>x</li>
    <li>y</li>
    <li>z</li>
  </ul>
</div>
<div id="boxB" tabindex="1">
...
</div>

From the docs:

In recent browser versions, the [focus] event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
0

Try this and tell me if it worked:

$("body").not("#boxA, #boxA ul li").live('focus', function(){ hideFunction(); });
Dimitris Damilos
  • 2,363
  • 5
  • 23
  • 46
0

Maybe something along these lines:

$('#boxA, #boxA > *').focusout(function () {
if ($(document.activeElement).closest('#boxA').length == 0){
    alert("not focused");
}
});

http://jsfiddle.net/AjT9j/3/

Flavien Volken
  • 19,196
  • 12
  • 100
  • 133
Taff
  • 231
  • 1
  • 13
-1

As this answer says, any element with a tabindex can receive focus, perhaps that's your answer.

Which HTML elements can receive focus?

Community
  • 1
  • 1
Ben Everard
  • 13,652
  • 14
  • 67
  • 96