child element taking focus from parent element

1

Is there any way to know when any child element is in focus? My problem revolves around the example below where I need a div not to blur when a child element is in focus (in this case any input element that serves for user interaction activates the onblur of the div):

(function divShow(){
  var div = document.getElementsByTagName('div');
  div.classList.toggle('active');
  div.addEventListener('blur', function(){
    div.classList.toggle('active');
  }, true);
})();
div {display: none}
div.active {display: block}
<div tabindex="-1">
  <header>My Tytle</header>
  <content>Hello world!!!</content>
  <footer>
    <button>My button</button>
  </footer>
</div>

I can identify when a first-level element is in focus and possibly make a if for the blur action, but I think there is a more useful way of handling that.

help?

    
asked by anonymous 16.06.2015 / 14:01

1 answer

3

This is the default behavior, but with one condition you can avoid this behavior.

var div = document.getElementsByTagName('div')[0];
div.classList.toggle('active');
div.addEventListener('blur', function(e){
  if (isChild(e.relatedTarget, this) || e.relatedTarget === this) {
    e.preventDefault();
    return;
  }
  div.classList.toggle('active');
}, true);

function isChild(child, parent) {
  while (child && (child = child.parentNode) && child !== parent);
  return !!child;
}
div {
  display: none;
}
div.active {
  display: block;
}
<div tabindex="-1">
  <header>My Tytle</header>
  <content>Hello world!!!</content>
  <footer>
    <button>My button</button>
  </footer>
</div>

The condition checks whether the element that caused blur ( e.relatedTarget ) is child or equal to the element that listens to the event and prevents default behavior with event.preventDefault() ;

Expected result: Clicking on any element of <div> is still visible, clicking away is hidden.

    
16.06.2015 / 16:08