Miller Mosquera Miller Mosquera - 3 months ago 9
HTML Question

Toggle the visibility of DIV's on click

I have one million

div
elements.

I want to achieve the following functionality:

1) When I click a vsibile
div
, it dissappears.

2) When I click a
div
, any
div
which was invisible reappears.

Example :

<div>1</div> <!-- Invisible div -->
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div> <!-- Currently visible. On click, div 1 becomes visible and this becomes invisible-->
... 1.000.000

Answer

prev = false;

document.querySelectorAll("#test div").forEach(function(a,i){
  a.index = i;
  a.addEventListener("click",function(){
  if (prev !== false) document.querySelectorAll("#test div")[prev].style.opacity = 1;
  this.style.opacity = 0;
  prev = this.index;
})});
#test * {
  width: 60px;
  height: 60px;
  margin: 10px;
  background-color: green;
}
<div id="test">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>