0

Is there a problem if i set same event handler and functionality on different elements?

I am trying to show a dropdown menu and when i click outside of it it should close, which approach is better? Because even when i select items inside the dropdown menu it still closes.

I don't know how to close the dropdown when i click outside so i tried to put both on header and body. But my result is something messy in the if statement.

I need to select for each element in the dropdown to be strict equal with the parentNode element.

E.g:

<div class="dropdown-menu">
 <ul>
  <li>Some link</li>
  <li>Some link</li>
  <li>Some link</li>
  <li>Some link</li>
 </ul>

  <ul>
   <li>Some link</li>
   <li>Some link</li>
   <li>Some link</li>
   <li>Some link</li>
  </ul>
</div>

When i click on a link or the ul it closes. I want only if i click outside of the dropdown menu

// Show dropdown more menu
 document.body.addEventListener('click', showMoreMenu);
 ui.header.addEventListener('click', showMoreMenu);

// Show dropdown more menu
function showMoreMenu(e) {
    ui.showMoreMenu(e);

    e.stopPropagation();
}

// Class method
showMoreMenu(e) {
    if(e.target === this.more_btn || e.target.parentElement === this.more_btn || e.target.parentNode === this.more_dropdown_menu || e.target === this.more_dropdown_menu || e.target.parentNode.parentElement === this.more_dropdown_menu) {
            this.more_dropdown_menu.classList.add('visible');
    } else {
        this.more_dropdown_menu.classList.remove('visible');
    }
}
Grecdev
  • 899
  • 9
  • 14

2 Answers2

0

I think this is what you need:

document.querySelector("body:not(.dropdown-menu)").addEventListener("click", showMoreMenu);
Dejvid
  • 470
  • 2
  • 13
0

I figured out the problem i just need it to add the .closest(selector) method.

Here you have browser support, and here i found a similar answer.

hideMenu(e) {
 if(!e.target.closest('.more-dropdown-menu')) {
  this.dropdown_menu.classList.remove('visible')
 }
}

window.addEventListener('click', eventOperations);

function eventOperations(e) {
 ui.hideMenu(e);

 e.stopPropagation();
}
Grecdev
  • 899
  • 9
  • 14