0

I have a button(.servicebutton) that when you click on it, it toggles classname ('active') for a menu which is called 'hdrmnu' and it opens menu, what I'm trying to do is that when I click anywhere else on the screen, 'active' gets removed.

my js

const servicebutton = document.querySelector('.servicebutton');
const hdrmnu = document.querySelector('.hdrmnu');
servicebutton.onclick = function(){
hdrmnu.classList.toggle('active');
}
Asraf
  • 1,322
  • 2
  • 12
Sadegh
  • 1
  • 1
  • Does this answer your question? [How do I detect a click outside an element?](https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element) – kmoser Nov 13 '22 at 18:58

1 Answers1

2

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

Ali Hamed
  • 316
  • 1
  • 1
  • 12