Miller Mosquera
Miller Mosquera

Reputation: 119

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 disappears.

  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

Upvotes: 3

Views: 82

Answers (1)

StardustGogeta
StardustGogeta

Reputation: 3406

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>

Upvotes: 1

Related Questions