vendredi 13 décembre 2019

Event delegation and looping through elements within if-statement

I have this project where I need to build a notification system into the site navigation bar. The “core” of the system has been implemented by using this delegated event listener approach that Chris at Go make things has recommended, where you listen to the DOM elements’ click events and it bubbles all the way up to the document.

So far it’s been working like a charm but I’ve been stuck in this one particular part where I need to loop through all the child elements within the popup element and include the looped elements in an if-statement.

I’ve tried all the different loop methods I could think of (for, while, forEach etc.) with more or less same result. Turning the selector variable (nodeList) manually into an array with Array.from won’t seem to do the trick either. Here’s a simplified version of my code:

const help_target = document.getElementById("help-target"),
  help_popup = document.getElementById("help-popup"),
  help_popup_all = document.getElementById("help-popup").querySelectorAll('*');

document.addEventListener("click", function(event) {

  // Reveal popup element       
  if(event.target == help_target && !help_target.classList.contains('active')) {
    help_popup_reveal();
  }

  // Hide popup element unless under these conditions
  if(event.target != help_target && help_target.classList.contains('active')) {
    for (let i = 0; i < help_popup_all.length; i++) {
      if(event.target != help_popup || event.target != help_popup_all[i]) {
        help_popup_hide();
      }
    }
  }
});
<div id="help">
  <p id="help-target">Need help?</p>
  <div id="help-popup">
    <p><b>Title</b></p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
  </div>
</div>

The help_popup_all[i] part in the if statement doesn’t work at all and clicking any of the elements that the variable should include runs the help_popup_hide function - which they shouldn’t do. The function should run only when clicked outside the popup while its active. The code works if I remove the for-loop and manually include all the elements the help_popup_all variable consist of.

So my question is: how do I properly include all the looped elements within my if statement? I’m open for alternative solutions as well.

Aucun commentaire:

Enregistrer un commentaire