简体   繁体   中英

Vanilla JS - Toggle class outside element

Like in topic. I search other way to do this, but it won't work good. After using button immediately function give me "removing" :/ Any lead to a good lead?

var button = document.querySelector(".menu-icon");
var menu = document.querySelector(".mymenu");

function drop(e){
  menu.classList.add("show");
  document.addEventListener("click", hide(e));
}
function hide(e){
  if(!menu.contains(e.target)) menu.classList.remove("show");
}
button.addEventListener("click", drop);

Well first of all, you need to parse the hide function into 'addEventListener', not call it, that will parse the return of the function (null), and call it immediately and not on click.

So it would look like this instead:

function drop(e) {
  menu.classList.add('show');
  document.addEventListener("click", hide); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM