When I do a search for images it loads images from Pixabay, which are added to a container via fetch without a page reload, I need to click on the newly generated images to get the ID of the image, which then converts the image ID to an URL, and gets added into the input.
My workaround is to find dom elements with the class ".dePixaImage" using the click
, and mouseover
event and then remove those events with removeEventListener
which works fine to a certain point, but then when I apply a new search nothing happens because the new dom elements are being loaded and the event listener has been stopped.
If I do not remove the removeEventListener
, then the for each loop keeps on multiplying, which results in a lot of fetch requests when the mouse is moved, or if a click occurs, which is completely unnecessary and uses up all the API requests.
window.addEventListener("click", deViewImage);
window.addEventListener("mouseover", deViewImage);
function deViewImage() {
let deViewImageAttr = "";
let dePixaImage = document.querySelectorAll(".dePixaImage");
if (dePixaImage) {
dePixaImage.forEach((e) => {
e.addEventListener("click", function () {
// id of the image from Pixabay, added via fetch
deViewImageAttr = e.getAttribute("id");
// call fetch function and pass ID
pixabayImageUrlFromId(deViewImageAttr);
});
window.removeEventListener("click", deViewImage);
window.removeEventListener("mouseover", deViewImage);
});
}
}
Maybe there is a better solution to listen for the dom elements when they get changed frequently?