On my page I have several divs with a class of products and each has its own data attribute. When the user clicks one of these divs, it opens a modal, gets data about the clicked div from the database based on the data attribute of the div, and lists the data in the modal. Then when the user clicks on one of the data listed in the modal it is supposed to be displayed in the div that was clicked on the page. The problem I am having is I cannot populate the clicked div with data from the modal as I will not have reference to it when using event delegation to grab the data from the modal. The following is my code snippet/ pseudo code
const prods = document.querySelectorAll(".products");
prods.AddEventlistener("clicked",(e)=>
fetch('some url').then(res => {
if (!res.ok) {
throw new Error("Cannot fetch resource!")
}
return res.json()
})
.then(
data => {
const arrayObject = JSON.parse(data.data);
arrayObject.forEach(prod => {
const markup = `<li>${prod.Info}></li>`;
document.querySelector('dialog ul').insertAdjacentHTML('beforeend', markup);
});
}).catch(error => console.log(error));
});
1 Like
define the clicked element globally when you open the modal. Your code for opening the modal knows what was clicked, and code inside the modal can access variables in the global space.
Hi thanks for your quick reply and your suggestion works great. I was trying to get direct access to the dynamically generated elements by putting code inside of the fetch method body itself circumventing the need for event delegation and a global variable to store the reference to the clicked div but it didn’t work.
Hey, you can store a reference to the originally clicked element in a global variable before opening the modal. Since event delegation doesn’t maintain a direct link to the clicked element after the modal interaction, you need to capture it at the moment of the click event and then use it later when updating the UI.
Try once. This is just my suggestion, hope this will help you.
let clickedElement = null; // Global variable to store reference
document.addEventListener("click", (e) => {
if (e.target.classList.contains("products")) {
clickedElement = e.target; // Store the clicked element
fetch("some-url")
.then((res) => {
if (!res.ok) throw new Error("Cannot fetch resource!");
return res.json();
})
.then((data) => {
const arrayObject = JSON.parse(data.data);
const listContainer = document.querySelector("dialog ul");
listContainer.innerHTML = ""; // Clear previous items
arrayObject.forEach((prod) => {
const markup = `<li data-info="${prod.Info}">${prod.Info}</li>`;
listContainer.insertAdjacentHTML("beforeend", markup);
});
})
.catch((error) => console.log(error));
}
});
// Event delegation inside modal
document.querySelector("dialog ul").addEventListener("click", (e) => {
if (e.target.tagName === "LI" && clickedElement) {
clickedElement.textContent = e.target.dataset.info; // Update original div
}
});