I’m sure there is a beginners mistake somewhere in there but here’s what I’m trying to do in vanilla js: I have a gallery with fetched works from an API. Each figure in the gallery has a delete button that deletes it from both the API and the gallery without a refresh. This works perfectly. However, I wanted to add a "Delete all" button that would delete everything upon confirming. The problem is: I can’t seem to make the loop work and it asks me to confirm for each figure.
Here’s my code:
deleteAllBtn.addEventListener("click", () => {
for (let figure of figureGallery) {
if (window.confirm("Are you sure you want to delete all your works?")){
while (figureGallery.length > 0) {
workId = figure.id
deleteFetch(workId)
figure.remove()
}}}
})
}
At first the for of was inside the if but it doesn’t work. I’ve tried using (figure) for the while too. I’ve tried (figureGallery), (figureGallery != 0)…
I’m sure this is very simple but I can’t seem to make it work.
Thanks for reading!
>Solution :
-
You are using a
for ... ofloop to iterate throughfigureGallery, but within that loop, you have awhileloop that is checking the length offigureGallery. This will create an infinite loop because you are not updating the length offigureGallerywithin the inner loop. -
The use of
window.confirmand thewhileloop seems redundant. You only need to show the confirmation once and then proceed to delete all the figures.
Here’s a revised version of your code:
deleteAllBtn.addEventListener("click", () => {
if (window.confirm("Are you sure you want to delete all your works?")) {
// Iterate through figureGallery and delete each figure
for (let figure of figureGallery) {
workId = figure.id;
deleteFetch(workId);
figure.remove();
}
// Clear the figureGallery array after deleting all figures
figureGallery = [];
}
});
In this code, we have removed the unnecessary while loop and adjusted the logic to show the confirmation only once. The loop will iterate through each figure in figureGallery, delete the work using deleteFetch, and remove the figure from the gallery. Finally, after deleting all figures, the figureGallery array is cleared.
Make sure that figureGallery is defined correctly and includes all the figure elements before using this code.