Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript How can I include document?addEventListener in this function.

Studi

New Coder
I have a few dropdown selection lists and want them to exit if you click anywhere on the site/document(make the aria-expanded false) because at the moment it exits only if you click on itself or one of the items inside the dropdown.


JavaScript:
const selection = document.querySelectorAll('.selection-selected');
const optionContainer = document.querySelectorAll('.options-container');

function toggleSelection() {
    const selectionToggle = this.getAttribute("aria-expanded");
    for (i = 0; i < selection.length; i++) {
      selection.setAttribute("aria-expanded", "false");
    }
    
    if (selectionToggle == "false") {
        this.setAttribute("aria-expanded", "true"); 
    }
}
selection.forEach(serviceItem => serviceItem.addEventListener("click", toggleSelection));

const channelSelection = document.querySelector('.channel');
const optionList = document.querySelectorAll('.channel-option');

optionList.forEach( o => {
  o.addEventListener("click", () => {
    channelSelection.innerHTML = o.querySelector("label").innerHTML;
    channelSelection.setAttribute("aria-expanded", "false");
    channelSelection.style.color = "#000";
    
  })
})

This is what I tried...

JavaScript:
for (i = 0; i < selection.length; i++) {
  if(selection.ariaExpanded == "true") {
    document.addEventListener('click', () => {
      selection.setAttribute("aria-expanded", "false");
    })
  }
}

If anyone could help me with this please, thank you!
 
Have you checked the console for any errors?
Yes, and I don't get any errors. But I can tell the if statement is not working the way I want. I mean without the if statement it's working properly but then I can't open the dropdown as it sets the aria expanded to false on all click when I want only after.
 

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom