Home > Net >  Show/hide div in JS
Show/hide div in JS

Time:05-05

I'm pretty fresh to JS.

For n amount of bar divs I have n amount foo divs. By clicking on bar[1], I want foo[1] to show or hide. The same goes for bar[2]/foo[2], bar[5]/foo[5], bar[3]/foo[3],...bar[n]/foo[n] in no exact order.

With this code I am able to show and hide, but only all of the divs at the same time. What should I change, so that I am able to hide or show only one of the divs?

function getContent() {
  var x = document.getElementsByClassName("foo");
  for (var i = 0; i < x.length; i  ) {
    if (x[i].style.display === "none") {
      x[i].style.display = "block";
    } else {
      x[i].style.display = "none";
    }
  }
}

document.querySelector(".bar").addEventListener("click", getContent);
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}

<div>
     <div  onclick="getContent()">bar</div>
</div>
<div >foo</div>

CodePudding user response:

No need to use JS here, HTML is more powerful than you think: if you want to show-or-hide information, the <details> element's got you covered.

.all-or-nothing summary {
  display: inline-block;
  cursor: pointer;
}
<details >
  <summary>Toggle all divs</summary>
  <div>
    The first div
  </div>
  <div>
    The second div
  </div>
    <div>
    The third div
  </div>
</details>

CodePudding user response:

Use a variable to hold the index of the current DIV to show, rather than looping over all the DIVs.

let fooIndex = 0;
let allFoo = document.querySelectorAll(".foo");

function getContent() {
  if (fooIndex < allFoo.length) {
    allFoo[fooIndex].classList.toggle("foo");
    allFoo[fooIndex].classList.toggle("bar");
    fooIndex  ;
  }
}

document.querySelector(".bar").addEventListener("click", getContent);
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}
<div>
  <div >bar</div>
</div>
<div >foo1</div>
<div >foo2</div>
<div >foo3</div>
<div >foo4</div>

CodePudding user response:

//let fooIndex = 0;

function getContent() {
    var x = $(".card");
    x.append('<div  onclick="hideContent(this)">foo1</div>');
    //$(this).addClass('bar');
  }

   function hideContent(a) {
    $(a).removeClass('foo');
    $(a).addClass('bar');
  }
.foo {
  display: none;
}

.bar {
  padding: 5px;
  display: block;
}
<div >
  <div onclick="getContent();" >bar</div>
</div>

  • Related