[ad_1]
I’m creating a list of modal through fetching local json file, but when I clicked the learn more button, all cards had the information of the last item.
const cards = document.querySelector(".cards");
async function getData() {
const response = await fetch("./modals/modal.json");
const data = await response.json();
console.log(data);
data
.map((item) => {
cards.innerHTML += `
<div class="card slide">
<img
src="${item.image}"
alt="${item.name}"
class="card--img"
/>
<h3>${item.name}</h3>
<button class="card--btn-light open-modal">Learn more</button>
</div>
<div class="modal">
<div class="modal-content">
<div class="modal--img">
<img src="${item.image}" alt="${item.name}" />
</div>
<div class="modal-desc">
<h3>${item.name}</h3>
<h4>${item.type}</h4>
<p>
${item.desc}
</p>
<p><strong>Age: </strong> ${item.age} months</p>
<p><strong>Inoculations: </strong>none</p>
<p><strong>Diseases: </strong> none</p>
<p><strong>Parasites: </strong> none</p>
</div>
<div class="close-modal">✕</div>
</div>
</div>
`;
})
.join("");
// ---------------modal
// works but only show last item
const modal = cards.querySelectorAll(".modal");
console.log(modal);
modal.forEach((item) => {
cards.addEventListener("click", (e) => {
if (e.target.classList.contains("open-modal"))
item.style.display = "flex";
if (e.target.classList.contains("close-modal")) {
item.style.display = "none";
}
window.addEventListener("click", (e) => {
if (e.target === modal) {
item.style.display = "none";
}
});
});
});
I am wondering how to show the right information of the clicked card. I have seen the solution of the modal issue but the content was generated from HTML, it’s a little different from this which the content was generated from fetching.
[ad_2]