Home > Enterprise >  How to stop .className when click anywhere on the screen
How to stop .className when click anywhere on the screen

Time:06-22

I have a function that makes an element appear when clicked, and make the other elements faded

const memberB = document.querySelectorAll('#memberA,#memberAA, #memberAAA ');
for (let i = 0; i < memberB.length; i  ) 
memberB[i].onclick = function(){
    memberA.className = "faded";
    memberAA.className = "faded";
    memberAAA.className = "faded";

    if(memberB[i].className=="open"){
        memberB[i].className="";
    }
    else{
        memberB[i].className="open";
    }
}

How do I make all memberB elements to be .className="" when click anywhere?

CodePudding user response:

use a single class for this for a more generic selector and I use this snippet to use a single event listener for this.

window.addEvent = (event_type, target, callback) => {
  document.addEventListener(event_type, function (event) {
    // If the event doesn't have a target
    // Or the target doesn't look like a DOM element (no matches method
    // Bail from the listener
    if (event.target && typeof (event.target.matches) === 'function') {
      if (!event.target.matches(target)) {
        // If the element triggering the event is contained in the selector
        // Copy the event and trigger it on the right target (keep original in case)
        if (event.target.closest(target)) {
          const new_event = new CustomEvent(event.type, event);
          new_event.data = { originalTarget: event.target };
          event.target.closest(target).dispatchEvent(new_event);
        }
      } else {
        callback(event);
      }
    }
  });
};

and then

window.addEvent('click', '.openable-member', (event) => {
  document.querySelectorAll('.openable-member').each((element) => {
    if (element !== event.target) {
      element.classList.add('faded');
      element.classList.remove('open'); // guessing you'll need this too
    }
  });

  event.target.classList.toggle('open');
});

CodePudding user response:

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

So you can map through memberB because it's not an array. What you can do is:

const memberB = document.querySelectorAll('#memberA,#memberAA, #memberAAA ');

memberB.onclick = function(){
    memberB.className = "faded";

    if(memberB.className == "open"){
        memberB.className = "";
    }
    else{
        memberB.className = "open";
    }
}

CodePudding user response:

You can try this:

memberB[i].className = memberB[i].className.replace("open", "");
  • Related