0

How can I get all my other .open-img elements to open my modal?

Eventually I want to trigger modals with the image inside, I'm sure I should be using .this, but cant get it to work.

Codepen: http://codepen.io/Middi/pen/EWxKLZ

Javascript

var modal = document.querySelector(".modal");
var modalBg = document.querySelector(".modal-bg");
var closeButton = document.querySelector(".close-button");
var openImg = document.querySelector(".open-img");

closeButton.addEventListener("click", function() {
  modal.classList.toggle("closed");
  modalBg.classList.toggle("closed");
});

this.openImg.addEventListener("click", function() {
  modal.classList.toggle("closed");
  modalBg.classList.toggle("closed");
});

Thanks in advance.

Middi
  • 343
  • 1
  • 3
  • 12

2 Answers2

1

You need to insert eventListener on your each open-img element.

for (var i = 0; i < openImg.length; i++) {
   openImg[i].addEventListener('click', function(){
    modal.classList.toggle("closed");
    modalBg.classList.toggle("closed");
   })
}

or use ES6 feature Array#from:

Array.from(openImg).forEach(v => v.addEventListener('click', function(){
    modal.classList.toggle("closed");
    modalBg.classList.toggle("closed");
}));

Codepen link

kind user
  • 40,029
  • 7
  • 67
  • 77
  • 1
    Amazing, So i just needed to iterate through the classes to attach an event listener. Thank you @Kind user. That will definitely help me in the future too. – Middi Feb 23 '17 at 13:49
0

Here's a solution based on your code. It's not perfect but it should give you a good starting point:

// get all the matching elements
var openImg = document.querySelectorAll(".open-img");

// iterate over them and add the handler for each of them
openImg.forEach(function (image) {
  image.addEventListener("click", function() {
    // append the image to the modal
    document.querySelector('.modal-main').appendChild(image.cloneNode(true))
    modal.classList.toggle("closed");
    modalBg.classList.toggle("closed");
  });
});
motanelu
  • 3,945
  • 1
  • 14
  • 21