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');
}
}