Mathias N
Mathias N

Reputation: 3

Close by clicking outside with plain javascript

I want to the menu to close (remove the class added when opened) when clicking outside the menu button area.

I got it all working but wondering if the code i put together is correct since I think the click outside should only be triggered when .newClass is added to the div. If so how do I add that? I'm quite new to javascript.

var b = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
  var clickOnMenu = b.contains(event.target);
  if (clickOnMenu) {
    b.classList.toggle("newClass");
  } else {
    b.classList.remove("newClass");
  }
});
div.box {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, 0.6);
  text-align: center;
  color: white;
  transition: .2s ease-in-out;
  cursor: pointer;
}

div.box:hover {
  background: rgba(0, 0, 0, 0.7);
}

div.newClass {
  padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>

Upvotes: 0

Views: 47

Answers (1)

Saeed
Saeed

Reputation: 5488

Hope this helps you

var b = document.getElementById("menu");
document.addEventListener("mouseup", function(event) {
  var x = event.target.id;
  if(x == "menu" ) {
    b.classList.add("newClass");
  } else {
    b.classList.remove("newClass");
  }
});
div.box {
  margin: auto;
  padding: 1em;
  max-width: 6em;
  background: rgba(0, 0, 0, 0.6);
  text-align: center;
  color: white;
  transition: .2s ease-in-out;
  cursor: pointer;
}

div.box:hover {
  background: rgba(0, 0, 0, 0.7);
}

div.newClass {
  padding-bottom: 100px;
}
<div id="menu" class="box">Menu</div>

Upvotes: 0

Related Questions