Hey there, I'm new to the world of JavaScript and trying my hand at creating multiple modals that pop up. Everything seems to be working fine when opening and closing each modal, but I keep encountering an error message in the console (Uncaught TypeError: Cannot read properties of null (reading 'style')) when trying to close them. It's been a real struggle for me to figure it out :(. Can someone please take a look at the code below and help me correct it? Any assistance would be greatly appreciated!
HTML
I've used images as buttons for this.
let imageButtons = document.querySelectorAll('img[data-modal], span.close');
let modals = document.querySelectorAll('.modal');
function openModals(id) {
let targetModal = document.getElementById(id);
targetModal.style.display = "block";
}
function closeModals() {
modals.forEach(modal => {
modal.style.display = "none";
});
}
imageButtons.forEach(button => {
button.addEventListener('click', event => {
closeModals();
openModals(button.dataset.modal);
});
});
modals.forEach(modal => {
let closeButton = modal.querySelector('.close');
closeButton.addEventListener('click', closeModals);
});
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
top: 0;
left: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.4);
}
.modal-content {
position: relative;
background-color: #78909C;
margin: auto;
padding: 0;
border: 1px solid white;
border-radius: 10px;
width: 50%;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
}
.close {
color: white;
float: right;
font-size: 20px;
}
.close:hover,
.close:focus {
color: #bbb;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
color: white;
text-align: center;
}
.modal-header h2 {
padding-top: 20px;
}
.modal-body {
padding: 2px 16px;
background-color: white;
margin: 20px;
border-radius: 10px;
}
<!-- Multiple Image Butto -->
<div class="image-slider fade">
<img src="img/1.png" alt="image" data-modal="project1">
<p>Image 1</p>
</div>
... (The rest of the HTML code continues here)
</div>