I’m trying to change the image that is displayed on the modal, but I get this error message when I try to target the img src:
Uncaught TypeError: Cannot set properties of null (setting ‘src’) . How do I fix this?
What am I doing wrong? Here is my codepen:
https://codepen.io/Montpellier81/pen/zYpyoEQ?editors=1111
HTML
<div class="container">
</div>
<div class="modal">
<div class="modal-content">
<i class ="modal-close">X</i>
<img id="modal-image" src="" alt="image">
<div class ="modal-info">
<h2 class="modal-name"></h2>
<h3 class="modal-location"></h3>
</div>
</div>
</div>
CSS
.container {
display: flex;
}
.card{
width: 300px;
height: 300px;
padding: 20px 20px;
cursor: pointer;
}
.modal {
position: fixed;
display: none;
z-index: 1;
left: 0; top: 0;
height: 100%;
width: 100%;
justify-content: center;
align-items: center;
background: rgba(0, 0, 0, 0.6);
}
.modal-content{
background-color: white;
padding-top: 150px;
margin: auto;
display: block;
width: 60%;
display: flex;
position: relative;
}
#modal-image{
width: 300px;
height: 150px;
border: 2px solid black;
justify-content: center;
}
.modal-close{
top: 15px;
right: 20px;
position: absolute;
color: red;
font-size: 30px;
cursor: pointer;
}
and JavaScript
const modal = document.querySelector('.modal');
const close = document.querySelector('.modal-close');
const attractions = [
{
"img": "https://montpellier81.github.io/landmarks/eiffel.jpg",
"name": "Eiffel Tower",
"place": "Paris, France",
},
{
"img": "https://montpellier81.github.io/landmarks/uluru.jpg",
"name": "Uluru, Ayers Rock",
"place": "Uluru-Kata Tjuta National Park, Australia",
},
{
"img": "https://montpellier81.github.io/landmarks/taj.jpg",
"name": "Taj Mahal",
"place": "Agra, India",
}
]
let html = '';
attractions.map((item, index) => {
html += `
<div id = '${index}' onclick = 'createModal(event)' class="card">
<div class="card-image">
<h2 class="name">${item.name}</h2>
<h3 class="place">${item.place}</h3>
<img id="image" src="${item.img}" alt="">
</div>
</div>
`
})
document.querySelector('.container').innerHTML = html;
function createModal(event){
let card = event.target.parentNode.parentNode
let index = parseInt(card.id)
let object = attractions[index]
let name = object.name
document.querySelector('.modal-name').innerText = name;
let locale = object.place
document.querySelector('.modal-location').innerText = locale;
let picture = object.img
document.querySelector('.modal-image').src = picture;
modal.style.display = "block";
close.onclick = function(){
modal.style.display = "none";
};
};