-3

I have written a simple JavaScript event listener for a JavaScript program I am currently building- I have written a simple modal which opens and closes on click but the on click does not seem to work. I am looping through JSON to display items for an eCommerce project as I am creating a new div for every new image could this be as to why the modal feature is not working?

var parentDiv = document.getElementsByClassName('items')

for (let i = 0; i < garments.hits.length; i++) {
  const child = document.createElement('div')
  child.setAttribute('class', 'style')
  const image = document.createElement('img')
  if (garments.hits[i].image) {
    image.setAttribute('src', garments.hits[i].image.link)
    image.setAttribute('alt', garments.hits[i].image.alt)
  }

  child.appendChild(image)
  parentDiv[0].appendChild(child)

  image.style.cssText = "height:550px; width:400px; cursor: pointer;"

  // function for modal bit 
  var modal = document.getElementById('simpleModal');
  // get open modal 
  var modalbtn = document.getElementsByClassName('style');
  // get close button
  var closeBtn = document.getElementsByClassName('closeBtn');

  // listen for click event 
  modalbtn.addEventListener('click', openModal);

  // function to open modal
  function openModal() {
    modal.style.display = 'block';
  }
.modal {
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.719);
  display: none;
}

.modal-content {
  background-color: #f4f4f4;
  margin: 20% auto;
  padding: 20px;
  width: 70%;
  box-shadow: 0 5px 8px rgba(0, 0, 0, 0.2), 0 7px 20px rgba(0, 0, 0, 0.2);
}

.closeBtn {
  color: #ccc;
  float: right;
  font-size: 30px;
}

.closeBtn:hover,
.closeBtn:focus {
  color: #000;
  text-decoration: none;
  cursor: pointer;
}
<div class="items">

  <div id="simpleModal" class="modal">
    <div class="modal-content">
      <span class="closeBtn">&times;</span>
      <p>?</p>
    </div>
  </div>
</div>
double-beep
  • 5,031
  • 17
  • 33
  • 41
Billy
  • 51
  • 7

1 Answers1

1

Here var modalbtn = document.getElementsByClassName('style');, modal button is a collection of elements. Therefore , modalbtn.addEventListener('click', openModal); wont work here.

Add

var modalbtn = document.getElementsByClassName('style');
modalbtn.forEach(function(button){
// listen for click event 
button.addEventListener('click', openModal); 
})

This will iterate through the elements and attach click event to it.

Akhil Aravind
  • 5,741
  • 16
  • 35
  • 1
    Or just do `document.addEventListener('click', function(e){ if(e.target && e.target.classList.contains('style')){ ... }});`. Since he's messing around with dynamic elements, I'd guess this is a more safer bet – icecub Feb 05 '20 at 11:50
  • @icecub thats too correct – Akhil Aravind Feb 05 '20 at 11:52