0

I am trying to toggle a popup when DIV is clicked. There is multiple DIV's that can be clicked and one popup each inside them.

So far what I have tried:

<div class="popup">Button1
   <span class="myPopup">Text inside popup</span>
</div>
<div class="popup">Button2
   <span class="myPopup">Text inside popup</span>
</div>

<script>
var el = document.querySelectorAll(".popup");
for(var i =0; i < el.length; i++) {
   el[i].onclick = function() { document.getElementsByClassName('myPopup')[i].classList.toggle("show")};
}
</script>

There will always be one popup inside one div, so I assumed if there is click event on div I can get element by class name (myPopup) and use same index to open myPopup, but I can't get it to work. Would like to get this done preferably only using JavaScript.

Newbie187
  • 17
  • 3
  • Does this answer your question? [How to pass arguments to addEventListener listener function?](https://stackoverflow.com/questions/256754/how-to-pass-arguments-to-addeventlistener-listener-function) – Run_Script May 04 '20 at 15:57
  • refer this https://stackoverflow.com/questions/19075104/how-to-toggle-switch-class-of-a-div-onclick-using-only-javascript – Sithija Siriwardana May 04 '20 at 15:59

2 Answers2

0

Instead of using

document.getElementsByClassName('myPopup')[i]

use

this.querySelector('.myPopup')

this refers to el so the query happens only inside of each el.

Instead of getElementsByClassName('myPopup')[i] we use querySelector('.myPopup') which always returns the first .mypopup within each el.

(Edited after good feedback provided by @Heretic Monkey)

var el = document.querySelectorAll(".popup");
for (var i = 0; i < el.length; i++) {
  el[i].onclick = function() {
    this.querySelector('.myPopup').classList.toggle("show");
  }
}
.myPopup {
  display: none;
}

.myPopup.show {
  display: block;
}
<div class="popup">Button1
  <span class="myPopup">Text inside popup1</span>
</div>
<div class="popup">Button2
  <span class="myPopup">Text inside popup2</span>
</div>
Tad Wohlrapp
  • 1,848
  • 1
  • 13
  • 18
0

This is a working example:

const elements = document.querySelectorAll(".popup")
elements.forEach(el => {
  el.onclick = function(event) {
    this.classList.toggle("show")
  }
})

https://jsfiddle.net/Buntel/8smdh5ou/9/

Seems you had an typo in classList.toggle()

Buntel
  • 540
  • 6
  • 19