Detect when container and children lose focus with jQuery

I want to determine when the HTML element and its children lose focus when the user clicks on the element. For instance:

<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 on an element in block A, it loses focus, but I want this to happen only when they press button "B" or somewhere else on the page.

Editing and Solution

I found this solution in Stack Overflow. This works for me:

Use jQuery to hide the div when the user clicks on it

+4
source share
5 answers

Try specifying the div a tabindex :

 <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 versions of the browser, the [focus] event can be expanded to include all element types, explicitly setting the element's tabindex property. An element can be focused using keyboard commands, such as the Tab key, or by clicking on the element.

+2
source

You can try to listen to the focusout event and then check if the current focus element is a child of your container, for example:

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

As stated in this answer, any element with tabindex can get focus, perhaps your answer.

What HTML elements can get focus?

0
source

Try this and tell me if this worked:

 $("body").not("#boxA, #boxA ul li").live('focus', function(){ hideFunction(); }); 
0
source

Maybe something like that:

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

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

0
source

Source: https://habr.com/ru/post/1446987/


All Articles