Ratic
Ratic

Reputation: 25

How to hide a div after pressing another div?

I've finally managed to make a div popup after a certain time in JS but the problem is, I can't get the div to disappear, I want to make it so the div disappear after being clicked but, how?

Sorry for asking but I've been looking for ages for something as simple as it sounds but I can't seem to figure out how to make a div clickable and then make it disappear when clicked thus I suppose don't have any important code to show.

Edit: It seems like showing some code is still important but it's quite simple though, just some code for making a div appear and how it should look. So here it is:

window.onload = function() {
  setTimeout(appeardiv, 30000);
}

function appeardiv() {
  document.getElementById("acceptbox3").style.display = "block"
}
.accept_square3 {
  background-color: rgb(255, 0, 0);
  position: fixed;
  top: 55.9%;
  left: 43.2%;
  height: 5vw;
  width: 13vw;
  display: none;
}
<div id="acceptbox3" class="accept_square3"></div>

Okay, I think this was all of the script.

Upvotes: 1

Views: 186

Answers (2)

YakovL
YakovL

Reputation: 8316

Sounds like what you need is just to add a click handler like so

function appeardiv() {
  const acceptBox = document.getElementById("acceptbox3");
  acceptBox.style.display = "block";
  acceptBox.onclick = () => acceptBox.remove();
}

If you are not familiar with arrow functions, you may also use ordinary functions:

  acceptBox.onclick = function() { acceptBox.remove() };

Also, if you need to add more than one handler, you may use

  acceptBox.addEventListener(() => acceptBox.remove());

instead.

The result is (let me decrease the timeout, though):

window.onload = function() {
  setTimeout(appeardiv, 1000);
}

function appeardiv() {
  const acceptBox = document.getElementById("acceptbox3");
  acceptBox.style.display = "block";
  acceptBox.onclick = () => acceptBox.remove();
}
.accept_square3 {
  background-color: rgb(255, 0, 0);
  position: fixed;
  top: 55.9%;
  left: 43.2%;
  height: 5vw;
  width: 13vw;
  display: none;
}
<div id="acceptbox3" class="accept_square3"></div>

Upvotes: 2

Toby
Toby

Reputation: 7

Not sure if I understand what you mean here. If you want to hide a div if cliccked, this should do the trick:

("#yourDiv").on("click", function() { ("#yourDiv").hide() });

Upvotes: -1

Related Questions