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">×</span>
<p>?</p>
</div>
</div>
</div>