child element taking focus of parent element

Asked

Viewed 159 times

1

Is there any way to know when some child element is in focus? My problem revolves around the example below where I need a div not to suffer the Blur when a child element is in focus (in this case, any input type element that serves for interaction with the active user 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 action of the Bank, but I believe that there is a more useful way to deal with this situation.

help?

  • 1

    With jQuery is simpler, you are not using?

  • @Kaduamaral, I fully agree that with Jquery is simpler, but the intention of the work I’m doing is to use everything that javascript can provide me, without manipulating the DOM (that’s why I’m with Angular). Jquery does its processing after page loading, and weighs in the matter of element handling. = D

  • 1

    You can try something with querySelector, or with the Parent property of GIFT.

  • I was thinking about something related to the same Lector but I saw that I was going to be doing countless laps... thanks

1 answer

3


This is the standard 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 the Blur (e.relatedTarget) is child or equal to the element that listens to the event and prevents the standard behavior with event.preventDefault();

Expected result: when clicking on any element of <div> it remains visible, when clicking outside it is hidden.

  • excellent, thanks, worked 100% in my solution

Browser other questions tagged

You are not signed in. Login or sign up in order to post.