Try to add event listener only when the menu is open. So, try to use
this way to solve your problem:
const html = document.documentElement;
const menu = document.getElementById('myMenuId');
function openMenu(){
// add class to the menu to make it show
menu.classList.add('animate');
// add event listener to the html element
html.addEventListener('click', closeMenuOnBodyClick);
}
and here to avoid some extra process we need to remove the event when
the menu is closed:
function closeMenu(){
// add class to the menu to make it show
menu.classList.remove('animate');
// add event listener to the html element
html.removeEventListener('click', closeMenuOnBodyClick);
}
Write the closeMenuOnBodyClick() function:
function closeMenuOnBodyClick(event){
// get the event path
const path = event.composedPath();
// check if it has the menu element
if (path.some(elem => elem.id === 'myMenuId')) {
// terminate this function if it does
return;
}
closeMenu();
}
I hope this solve your problem.
regards